XMLHttpRequest 已被 CORS 策略阻止:请求 header 字段 content-type 不允许在飞行前响应中被 Access-Control-Allow-Headers

XMLHttpRequest has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

由于 CORS,我在从表单创建新用户时遇到问题。上周我能够使用这个应用程序,但不确定我的服务器(方法、来源、headers 等)或我的 API 调用中缺少什么。

以下是控制台问题部分的建议:

要解决此问题,请在相关预检请求的 Access-Control-Allow-Headers 响应 header 中包含您要使用的其他请求 header。 1 个请求 请求状态预检请求不允许请求 Header new_user 已阻止 new_usercontent-type

服务器代码如下:

require('dotenv').config();
const express = require('express');
const cors = require('cors');

const app = express();

// Cookies:
const cookieParser = require('cookie-parser');

require('./config/mongoose.config');
app.use(cookieParser());

//required for post request
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// routes:
require('./routes/user.routes')(app);
require('./routes/spot.routes')(app);


// blocking cors errors:
const corsOptions = {
    origin: 'http://localhost:3000',
    methods: ["GET", "POST"],
    allowedHeaders: ["*"],
    credentials: true,            //access-control-allow-credentials:true
    optionSuccessStatus: 200,
}
app.use(cors(corsOptions)) // Use this after the variable declaration


//  MIDDLEWARE:
// app.use(cors(
//     { credentials: true, origin: 'http://localhost:3000' },
//     { headers: { "Access-Control-Allow-Origin": "*" } }));


// Middleware CORS API CALLS: 
app.use((req, res, next) => {
    if (req.method === "OPTIONS") {
        res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET", true);
        return res.status(200).json({});
    }
    next();
});

//listen on port:
app.listen(9000, () => {
    console.log("Listening at Port 9000")
})

路线如下:

const UserController = require('../controllers/user.controllers');
const { authenticate } = require('../config/jwt.config');
module.exports = function (app) {
    app.post('/api/new_user', authenticate, UserController.register);
    app.get('/api/users', UserController.getAllUsers);
    app.get('/api/users/:id', UserController.login);
    app.post('/api/users/logout', UserController.logout);
    app.put('/api/users/:id', UserController.updateUser);
    app.delete('/api/users/:id', UserController.deleteUser);
}

这里是客户端(表单代码):

const onSubmitHandler = e => {
        e.preventDefault();

        const { data } =
            axios.post('http://localhost:9000/api/new_user', {
                userName,
                imgUrl,
                email,
                password,
                confirmPassword
            },
                { withCredentials: true, },
                // { headers: { 'Access-Control-Allow-Origin': '*' } }
                { headers: ["*"] }
            )
                .then(res => {
                    history.push("/dashboard")
                    console.log(res)
                    console.log(data)
                })
                .catch(err => console.log(err))

我做了一些研究,不确定是否应该制作代理、使用插件等,但我可以使用额外的眼睛。谢谢大家!

我认为是这条线造成的return res.status(200).json({}); 当您响应 CORS 预检时,您不应该包含 Content-Type 并将 return 类型设置为 JSON 可能正是这样做的。

尝试

res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.status(200).end();

如果您已经在使用 cors middleware, you don't need to manually handle OPTIONS requests, it does that for you

删除此部分...

// Middleware CORS API CALLS: 
app.use((req, res, next) => {
    if (req.method === "OPTIONS") {
        res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET", true);
        return res.status(200).json({});
    }
    next();
});

您还应该在您的路由之前注册 cors 中间件,以及您的其他中间件。

app.use(cors({
  origin: "http://localhost:3000",
  credentials: true,            //access-control-allow-credentials:true
  optionSuccessStatus: 200,
}))

//required for post request
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// routes:
require('./routes/user.routes')(app);
require('./routes/spot.routes')(app);

在 client-side 上,["*"] 是无效请求 header,需要删除。您也没有正确处理异步响应。应该是

axios.post("http://localhost:9000/api/new_user", {
  userName,
  imgUrl,
  email,
  password,
  confirmPassword
}, { withCredentials: true, }).then(res => {
  history.push("/dashboard")
  console.log(res)
  console.log(res.data) //  this is where `data` is defined
}).catch(console.error)