尽管添加了适当的标题,但仍被CORS策略错误阻止
我正在尝试将我的React应用程序中的HTTP请求发送到其他端口上的本地服务器。但是,每次我发送发布http请求时,此错误都会发生:
我在React应用中拥有的代码:
const handleSubmit = async (e) => {
e.preventDefault();
const data = {ingredientInput};
console.log(data.ingredientInput);
console.log(JSON.stringify(data));
const response = await fetch('http://localhost:5000/verify', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(data),
});
这是我在服务器中拥有的代码。
const express = require('express');
const router = express.Router();
let bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
})
const PORT = 5000;
const app = express();
app.use(express.json());
const fs = require('fs');
app.post('/verify', (req, res) => {
console.log(req.body);
})
我已经添加了浏览器状态的标题,例如“访问控制”标题,但CORS错误仍会发生。有人可以告诉我问题是什么吗?
I am trying to send an HTTP request from my React app to my local server on a different port. However, every time I send a POST HTTP request, this error happens:
This is the code I have in my React app:
const handleSubmit = async (e) => {
e.preventDefault();
const data = {ingredientInput};
console.log(data.ingredientInput);
console.log(JSON.stringify(data));
const response = await fetch('http://localhost:5000/verify', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(data),
});
This is the code I have in my server.
const express = require('express');
const router = express.Router();
let bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
})
const PORT = 5000;
const app = express();
app.use(express.json());
const fs = require('fs');
app.post('/verify', (req, res) => {
console.log(req.body);
})
I have added the headers that the browser states such as the 'Access-Control-Allow-Origin' header but the CORS error still happens. Would anyone be able to tell me what the issue is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用路由器。
You need to use the router.