从源“..”获取“..”的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述 投票:0回答:1

为我的 MERN 应用程序尝试 post 方法,出现以下错误。我该如何解决这个问题?

完整错误:

访问从源地址“http://localhost:8000/register”获取 “http://localhost:3000”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

注册.js

    // 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))
    }

index.js

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'
    });
})
reactjs node.js express cors http-headers
1个回答
0
投票

以下对我的 Node.js 和 React 的更改对我有用:

将cors添加到我的快递中:

index.js

const cors = require("cors");
const corsOptions = {
   origin: '*', 
   credentials: true,           
   optionSuccessStatus: 200,
}
app.use(cors(corsOptions)) 
将正文字符串化并将“Content-Type”标头设置为 json:

注册.js

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))
© www.soinside.com 2019 - 2024. All rights reserved.