我正在嘗試使用 nodeJS 服務器和 React 客戶端應用程式將檔案上傳到 aws S3。我是 aws 的新手,所以我想我做錯了什么。我創建了一個完全私有的后臺,以便只有應用程式可以訪問檔案。問題是,當我想上傳檔案時,我需要獲取鏈接 myBucket.getSignedUrl () 才能上傳它。當我這樣做并將其發送到前端時,前端使用我要上傳的檔案獲取到 S3 的鏈接,問題是它回傳以下錯誤:
訪問在 'https://atlasworld-progress.s3.amazonaws.com/IMG_20210202_100322.jpg?AWSAccessKeyId=AKIAZGHWWSFL5XOWPRXJ&Content-Type=image/jpeg&Expires=1633937718&8ONdM3020202_100322.jpg?已被 CORS 策略阻止:對預檢請求的回應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。如果不透明回應滿足您的需求,請將請求的模式設定為“no-cors”以在禁用 CORS 的情況下獲取資源。
這是aws組態檔:
import AWS from 'aws-sdk'
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY
})
const S3_BUCKET ='atlasworld-progress';
const REGION =process.env.AWS_REGION;
const URL_EXPIRATION_TIME = 60; // in seconds
const myBucket = new AWS.S3({
params: { Bucket: S3_BUCKET},
region: REGION,
})
export const generatePreSignedPutUrl = async (fileName, fileType) => {
const url = await myBucket.getSignedUrl('putObject', {
Key: fileName,
ContentType: fileType,
Expires: URL_EXPIRATION_TIME
});
return url;
}
在快速控制器中,它只是將函式 generatePreSignedPutUrl() 生成的鏈接回傳給客戶端。這是 React 中前端函式的代碼:
const [frontPhoto, setFrontPhoto] = useState();
const upload = async (e) => {
e.preventDefault();
await JWT.checkJWT();
const requestObject = {
fileName: frontPhoto.name,
fileType: frontPhoto.type,
token: JWT.getToken()
};
axiosReq.post(`${serverPath}/prepare_s3`, requestObject).then((res) => {
//the following fetch is the one that fails
fetch(res.data, {
method: "PUT",
body: frontPhoto,
}).then((res) => {
console.log(res);
});
});
}
如果有人知道發生了什么,我將不勝感激。
我還想問一下,S3 是一次只能上傳一個檔案還是可以一次上傳不同的檔案。
謝謝!
uj5u.com熱心網友回復:
我認為這說明了一切:
從源“http://localhost:3000”獲取的訪問已被 CORS 策略阻止
您需要熟悉CORS。如果您希望它起作用,那么您需要從 AWS 啟用 CORS。
uj5u.com熱心網友回復:
這是一個 nginx 配置問題,你必須在 nginx.conf 中增加你的client_max_body_size
腳步:
通過 ssh 連接到您的 Beanstalk/EC2 實體:
ssh -i <key.pem> <ec2-user>@<host>以超級用戶身份登錄:
$ sudo su編輯 nginx.conf
nano /etc/nginx/nginx.conf在 http 塊中添加這一行
client_max_body_size 50M;保存存檔
重啟nginx服務
$ service nginx restart
示例 NGINX 組態檔
# Elastic Beanstalk Nginx Configuration File
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
client_max_body_size 50M; --------- add this line
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
log_format healthd '$msec"$uri"$status"$request_time"$upstream_response_time"$http_x_forwarded_for';
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318855.html
