在过去的几个小时中浏览SO可以找到针对我的问题的解决方法,但是目前还没有任何进展
所请求的资源上没有“ Access-Control-Allow-Origin”标头。
现在,通常可以通过在代码中添加适当的标头来解决此问题,并且可以正常工作,但是对我而言情况并非如此,因为我尝试通过AWS上的API Gateway配置cors。
Google上的一些研究提到,如果该函数使用lambda代理集成,我们将不得不修改lambda本身,并通过自己添加标头,例如
headers: {
'Access-Control-Allow-Origin': '*',
},
但这没什么大不了,我想念什么吗?
我的lambda实际代码(忘记添加):
const rp = require('request-promise')
const sendEmail = require('./sendEmail')
module.exports.run = async (event, context, callback) => {
const body = JSON.parse(event.body)
const { name, email, budget, message, attachment } = body
if (!name) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Name is required' }),
})
}
if (!email) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Email address is required' }),
})
}
if (!message) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Message is required' }),
})
}
return Promise.all([
sendEmail({
to: 'Example <user@example.com>',
subject: 'New enquiry received!',
data:
`Name: ${name}\n` +
`Email: ${email}\n` +
`Budget: ${budget || 'n/a'}\n` +
`Attachment: ${attachment || 'n/a'}\n` +
`\n${message}`,
}),
sendEmail({
to: `${name} <${email}>`,
subject: 'Your message was delivered at ',
data:
'Thanks for reaching out!\n' +
'Somebody at our office will get back to you as soon as possible.\n' +
'\n' +
'While you wait, check out our Handbook (/) and get acquainted with how we do things around here.\n' +
'We have a lot of content there so feel free to explore as you please.\n' +
'\n' +
'Speak soon,\n' +
'\n',
}),
rp({
method: 'POST',
uri: `https://hooks.slack.com/services/${process.env.SLACK_PATH}`,
json: true,
body: {
text: `<!channel> New enquiry received`,
attachments: [
{
fallback: 'Information:',
pretext: 'Information:',
color: '#FF5050',
fields: [
{ title: 'Name', value: name, short: false },
{ title: 'Email', value: email, short: false },
{ title: 'Budget', value: budget || 'n/a', short: false },
{ title: 'Attachment', value: attachment || 'n/a', short: false },
{ title: 'Message', value: message || 'n/a', short: false },
],
},
],
},
}),
])
.then(() => {
return callback(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({ message: 'Great success' }),
})
})
.catch(err => {
return callback(null, {
statusCode: 500,
body: JSON.stringify({
message: 'Oh no :( Message not delivered',
error: err
}),
})
})
}
答案 0 :(得分:1)
所请求的资源上没有“ Access-Control-Allow-Origin”标头。
这表示您通过API网关请求的Lambda资源未在其响应中返回Access-Control-Allow-Origin
标头;浏览器期望API响应中包含CORS标头(可能是由于OPTIONS请求),但响应中没有它们。
要解决您的问题,请在Lambda返回的响应中添加Access-Control-Allow-Origin: *
标头。使用您要返回的第一项:
if (!name) {
return callback(null, {
statusCode: 400,
headers: {
'Access-Control-Allow-Origin': '*',
// any other required headers
},
body: JSON.stringify({ message: 'Name is required' }),
})
}
值得一提的是,您必须将这些标头添加到每个响应中。