我正在开发一个项目
- 我的 API 是用 Express.js (4.16) 编写的 - 端口: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]
作品 - 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);
}
});
但是我得到请求的资源上不存在“Access-Control-Allow-Origin” header 。
错误!
但在这种情况下,至少在我的 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'
错误。 - 我做错了什么?
谢谢大家!
最佳答案
由于 1337
和 3000
是不同的端口,因此您会遇到 CORS请求。
首先,在获取请求中设置mode: cors
,然后添加路由器处理程序
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
处理程序之前。
完成此操作后,您就可以开始了。
关于javascript - 使用 Fetch API 时无法获取请求正文,但 JQuery AJAX 可以工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49399820/