【发布时间】:2020-10-21 06:46:53
【问题描述】:
我已经把头撞在墙上好几个小时了……尝试了各种组合来让它发挥作用。
我在这里有自己的 API 端点:https://app.automate.mn/api/tools/email/add
我正在尝试从 3rd 方网站向其发布数据。
app.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.options('*', cors());
...
const {addContact} = require('./routes/api/tools/email');
app.post('/api/tools/email/add', addContact);
addContact.js
addContact: async function (req, res) {
res.status(200).send('OK - TEST');
return;
}
我在这里设置了一个测试网站,格式为:https://demoautomatemn.wpcomstaging.com/
当您提交表单时,它会将数据发布到端点:
loadForm.js
automate_post_data('https://app.automate.mn/api/tools/email/add', data)
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
async function automate_post_data(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
//referrerPolicy: 'origin', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
}
return response.json();
}
帖子失败:
Access to fetch at 'https://app.automate.mn/api/tools/email/add' from origin 'https://demoautomatemn.wpcomstaging.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
loadForm.js:109 POST https://app.automate.mn/api/tools/email/add net::ERR_FAILED
我希望在 OPTION 调用的响应标头中看到“Access-Control-Allow-Origin”,但什么也没有(Preflight response is not successful)。我已尽一切努力让它发挥作用。
现在欢迎任何建议。
【问题讨论】:
标签: express http-status-code-406