尝试使用 Axios 向 API 发送 POST 请求时,响应中的“Access-Control-Allow-Credentials"标头为"" [英] 'Access-Control-Allow-Credentials' header in the response is ' ' when trying to send a POST request to an API using Axios

查看:44
本文介绍了尝试使用 Axios 向 API 发送 POST 请求时,响应中的“Access-Control-Allow-Credentials"标头为""的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 localhost:3000 上运行的 react 应用程序和一个在 localhost:8000 上运行的 nodeJS-express 服务器,我需要向 jsreport API 发送一个 POST 请求,但是当我尝试发送请求时,我收到以下错误:

<块引用>

在 'http://localhost:5488/api/report' 从源访问 XMLHttpRequest'http://localhost:3000' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:响应中Access-Control-Allow-Credentials"标头的值为",当请求的凭据模式为包含"时,该值必须为真".XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制.

发布请求:

axios.defaults.withCredentials = true;axios.post('http://localhost:5488/api/report',{withCredentials: true, crossorigin: true},{模板": {"content": "

你好{{foo}}

","engine": "车把",食谱":铬-pdf"},数据": {"foo": "世界"}}).then((响应)=>{fs.writeFileSync('/reports/report.pdf', response.content)}).catch(函数(错误){console.log('AXIOS 错误:'+ 错误);返回'错误报告'})

Server.js:

var corsOptions = {来源:'http://localhost:3000',凭据:真实}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('未找到');错误状态= 404;下一个(错误);})

如果我在 axios 中使用 .withCredentials 并在服务器中建立标头和 cors 配置,我不明白为什么凭据为空.

解决方案

我使用了下一个代码而不是 axios 请求并且它有效:

fetch('http://localhost:5488/api/report', {方法:'POST',正文:JSON.stringify(数据),标题:{'内容类型':'应用程序/json'},凭据:同源",}

将凭据设置为同源"解决了这个问题,但是当我想使用 jsreport 时,我找到了一个包,可以在不使用 fetch 或 axios 的情况下使这更容易.

从'jsreport-browser-client-dist'导入jsreportjsreport.serverUrl = 'http://localhost:5488'jsreport.render(document.getElementById('reportPlaceholder'), 数据)

使用 jsreport 方法我可以在 react 组件中显示我的报告

<p>这里应该有一份报告...</p>

I have a react app running in localhost:3000 and a nodeJS-express server on localhost:8000, I need to send a POST request to the jsreport API, but when I try to send the request I got the following error:

Access to XMLHttpRequest at 'http://localhost:5488/api/report' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Post request:

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'
})

Server.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);
})

I don't understand why the credentials are empty If I use .withCredentials in axios and established the headers and the cors configuration in the server.

解决方案

I used the next code instead of the axios request and it worked:

fetch('http://localhost:5488/api/report', {
  method: 'POST',
  body: JSON.stringify(data),
  headers:{
    'Content-Type': 'application/json'
  },
  credentials: "same-origin",
}

Set credentials to "same-origin" fixed the problem, but as I wanted to use jsreport I found a package to make this easier without using fetch or axios.

import jsreport from 'jsreport-browser-client-dist'
jsreport.serverUrl = 'http://localhost:5488'
jsreport.render(document.getElementById('reportPlaceholder'), data)

Using the jsreport methods I could show my report in the react component

<div id="reportPlaceholder">
      <p>there should be a report here...</p>
</div>

这篇关于尝试使用 Axios 向 API 发送 POST 请求时,响应中的“Access-Control-Allow-Credentials"标头为""的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆