为我的 MERN 应用程序尝试 post 方法,出现以下错误。我该如何解决这个问题?
访问从源地址“http://localhost:8000/register”获取 “http://localhost:3000”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
// this function executes on click of Register button
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:8000/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: {
"hi": "world"
}
})
.then((res) => res.json())
.then((data) => {
if(data.status==='success') {
console.log(data.status)
}
})
.catch(e => console.log(e))
}
const express = require('express');
require('dotenv').config()
const app = express();
var bodyParser = require('body-parser')
const port = process.env.PORT;
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
// Add headers before the routes are defined
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
next();
});
app.listen(port, () => {
console.log('Listening on port ' + port);
});
app.post('/register', async (req, res) => {
res.json({
status: 'success'
});
})
以下对我的 Node.js 和 React 的更改对我有用:
const cors = require("cors");
const corsOptions = {
origin: '*',
credentials: true,
optionSuccessStatus: 200,
}
app.use(cors(corsOptions))
fetch('http://localhost:8000/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"hi": "world"
})
})
.then((res) => res.json())
.then((data) => {
if(data.status==='success') {
console.log(data.status)
}
})
.catch(e => console.log(e))