【问题标题】:Not getting request body when using Fetch API but JQuery AJAX works.使用 Fetch API 时未获取请求正文,但 JQuery AJAX 有效。
【发布时间】:2018-08-30 04:31:30
【问题描述】:

我正在做一个项目

  1. 我的 API 是用 Express.js (4.16) 编写的 - 在 PORT: 1337 中
  2. 前端应用程序位于 React.js (16.2) - 端口:3000

所以我需要从 React.js 应用程序调用几个 API,我面临的问题是:

问题是 -

根本不起作用-fetch() API

fetch('localhost:1337/rest/api', {
    body: JSON.stringify( {name: "Sidd", "info": "Lorem ipsum dolor .."} ),
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    mode: 'no-cors',
    method: 'post'
})

当我使用fetch() API 时,我没有在 Express.js 中定义的 API 中获取请求正文

console.log(req.body) // On logging the request body
{} // am getting this [empty]

WORKS-jQuery AJAX

$.ajax('localhost:1337/rest/api', {
    type: 'post',
    data: {name: "Sidd", "info": "Lorem ipsum dolor .."},  
    dataType: 'application/json',
    success: function (data, status, xhr) {
        console.log('status: ' + status + ', data: ' + data);
    },
    error: function (jqXhr, textStatus, errorMessage) {
        console.log('Error' + errorMessage);
    }
});

但是我收到No 'Access-Control-Allow-Origin' header is present on the requested resource. 错误!

但在这种情况下,至少是 GETTING 我的 API 中的请求正文。还通过 POSTMAN 测试了我的 API,它们工作得很好。 我在网上看到了所有的讨论,但没有任何效果。

哦!我还想添加这个 - 在我的 Express.js 设置中正确使用 body-parser

app.use(bodyParser.json({limit: '2mb'}));                           // 2mb file upload limit
app.use(bodyParser.urlencoded({limit: '2mb', extended: true}));     // 2mb file upload limit

我想要什么!

  1. fetch() API 的解决方案
  2. 如果不是 fetch() API,如何从我的 jQuery Ajax 调用中删除 No 'Access-Control-Allow-Origin' 错误。
  3. 我做错了什么?

谢谢大家!

【问题讨论】:

标签: javascript jquery node.js reactjs fetch-api


【解决方案1】:

由于13373000 是不同的端口,所以你遇到了CORS 请求。

首先在fetch request中设置mode: cors,然后添加router handler

router.use((req, res, next) => {
  res.header('access-control-allow-origin', 'http://localhost:3000')
  res.header('Access-Control-Allow-Credentials', true)
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('Access-Control-Max-Age', 1728000)
  if (req.method === 'OPTIONS') {
    return res.json({ status: 0, message: '', payload: null })
  }
  next()
})

在您的 rest/api 处理程序之前。

完成后,您就可以开始了。

【讨论】:

  • 它会解决 cors prob +1 的问题,但是 [fetch API] 呢?有什么线索吗?
  • 您可以阅读Using Fetch 文档了解更多详细信息。如果您对mode 属性感到困惑,请查看Request()
  • 您的回答帮助我意识到我需要在 Django 应用程序中允许我的 CORS 相关设置上的凭据。所以谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2013-08-20
  • 1970-01-01
  • 2017-11-27
  • 2018-12-09
  • 2021-08-02
  • 2013-05-12
相关资源
最近更新 更多