【发布时间】:2018-08-30 04:31:30
【问题描述】:
我正在做一个项目
- 我的 API 是用 Express.js (4.16) 编写的 - 在 PORT: 1337 中
- 前端应用程序位于 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
我想要什么!
- fetch() API 的解决方案
- 如果不是 fetch() API,如何从我的 jQuery Ajax 调用中删除
No 'Access-Control-Allow-Origin'错误。 - 我做错了什么?
谢谢大家!
【问题讨论】:
标签: javascript jquery node.js reactjs fetch-api