我有一个在 localhost:3000 上运行的 react 应用程序和一个在 localhost:8000 上运行的 nodeJS-express 服务器,我需要向 jsreport API 发送一个 POST 请求,但是当我尝试发送请求时,我收到以下错误:
从源“ http://localhost:3000 ”访问 XMLHttpRequest at ' http://localhost:5488/api/report '已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:的值响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“包含”时,该标头必须为“真”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
发布请求:
axios.defaults.withCredentials = true;
axios.post('http://localhost:5488/api/report',
{withCredentials: true, crossorigin: true},
{
"template": {
"content": "<h1>Hello {{foo}}</h1>",
"engine": "handlebars",
"recipe": "chrome-pdf"
},
"data": {
"foo": "world"
}
}).then((response)=> {
fs.writeFileSync('/reports/report.pdf', response.content)
}).catch(function (error) {
console.log('AXIOS error: '+ error);
return 'errorReport'
})
服务器.js:
var corsOptions = {
origin: 'http://localhost:3000',
credentials : true
}
app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header('Access-Control-Expose-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
const err = new Error('Not Found');
err.status = 404;
next(err);
})
如果我在 axios 中使用 .withCredentials 并在服务器中建立标头和 cors 配置,我不明白为什么凭据为空。