我有一个React前端,该式允许用户添加和查看包含文本和图片的配方。后端是一个express node.js应用程序,从读取并写入DynamoDB数据库。该应用程序使用无服务器框架部署在AWS上,因此它使用API网关,Lambda,DynamoDB和S3进行照片存储。我正在努力使上载路线正常工作,但是CORS错误阻止了它的工作。
我已经导入了CORS NPM模块,并且正在应用程序上使用它。我已经尝试过说明配置中的原点的explicity,但这没有区别。我也有CORS:在我的serverless.yml文件中的每个路由上进行true。
serverless.yml excerpt:
service: recipes-api
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: us-east-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
- { "Fn::GetAtt": ["RecipesDynamoDBTable", "Arn"] }
environment:
RECIPES_TABLE: ${self:custom.tableName}
S3_BUCKET: ${self:custom.bucketName}
functions:
app:
handler: index.handler
events:
- http: ANY /
- http: 'ANY {proxy+}'
getRecipe:
handler: index.handler
events:
- http:
path: recipes/{name}
method: get
cors: true
allRecipes:
handler: index.handler
events:
- http:
path: allrecipes
method: get
cors: true
addRecipe:
handler: index.handler
events:
- http:
path: recipes
method: post
cors: true
uploadPhoto:
handler: index.handler
events:
- http:
path: uploadphoto
method: post
cors: true
getPhoto:
handler: index.handler
events:
- http:
path: photo/{name}
method: get
cors: true
index.js excerpt:
const serverless = require('serverless-http');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');
const cors = require('cors');
...
app.use(cors({origin: 'https://recipes.example.co'}))
//Upload Photo Endpoint
app.post('/uploadphoto', function (req, res) {
const s3 = new AWS.S3(); // Create a new instance of S3
const fileName = req.body.fileName;
const fileType = req.body.fileType;
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 500,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if(err){
console.log(err);
res.json({success: false, error: err})
}
// Data payload of what we are sending back, the url of the signedRequest and a URL where we can access the content after its saved.
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
// Send it all back
res.json({success:true, data:{returnData}});
});
})
AddRecipeForm.js excerpt:
handleUpload = (ev) => {
console.log("handleUpload")
console.log(ev)
let file = this.uploadInput.files[0];
// Split the filename to get the name and type
let fileParts = this.uploadInput.files[0].name.split('.');
let fileName = fileParts[0];
let fileType = fileParts[1];
console.log("Preparing the upload");
axios.post("https://bqdu4plthq.execute-api.us-east-1.amazonaws.com/dev/uploadphoto",{
fileName : fileName,
fileType : fileType
})
.then(response => {
var returnData = response.data.data.returnData;
var signedRequest = returnData.signedRequest;
var url = returnData.url;
this.setState({url: url})
console.log("Recieved a signed request " + signedRequest);
// Put the fileType in the headers for the upload
var options = {
headers: {
'Content-Type': fileType
}
};
axios.put(signedRequest,file,options)
.then(result => {
console.log("Response from s3")
this.setState({success: true});
})
.catch(error => {
console.error(error);
})
})
.catch(error => {
console.error(error);
})
}
单击"上传照片"按钮,该按钮在AddRecipeform.js中调用handleupload funciton时,我在控制台中会收到以下错误:
Origin https://recipes.example.co is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load https://bqdu4plthq.execute-api.us-east-1.amazonaws.com/dev/uploadphoto due to access control checks.
Failed to load resource: Origin https://recipes.example.co is not allowed by Access-Control-Allow-Origin.
请注意,其他所有路线都可以使用(getRecipe,allrecipes,addRecipe(并发送CORS标题,因此我不确定为什么我的AddPhoto请求来自API Gateway的AddPhoto请求,即使应该使用它,即使它应该使用它在index.js中。预先感谢您的帮助!
您的serverless.yml具有默认定义的函数'app',这是一个接收路线({proxy }匹配全部(。看来这是您要遇到的路线,而不是上载photo,因为您的上载路由是将方法定义为方法帖子,但是您的前端Axios请求正在使用。
除了所有其他Q/A上所述的所有技术内容(要添加(,请确保您的功能在29秒内返回对前端的响应。这是您响应的默认超时(和最大超时(设置。修复此操作后,我能够打破CORS错误。