【问题标题】:XMLHttpRequest has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight responseXMLHttpRequest 已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型
【发布时间】:2022-01-10 22:59:07
【问题描述】:

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

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

要解决此问题,请在关联的预检请求的 Access-Control-Allow-Headers 响应标头中包含您要使用的其他请求标头。 1 个请求 请求状态 Preflight Request Disallowed 请求标头 新用户被阻止 new_user 内容类型

这是服务器代码:

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

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

【问题讨论】:

    标签: javascript express axios cors


    【解决方案1】:

    如果您已经在使用cors middleware,则无需手动处理OPTIONS 请求,它是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);
    

    在客户端,["*"] 是无效的请求标头,需要删除。您也没有正确处理异步响应。应该是

    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)
    

    【讨论】:

      【解决方案2】:

      我认为是这条线引起的return res.status(200).json({}); 当您响应 CORS 预检时,您不应该包含 Content-Type 并将返回类型设置为 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();
      

      【讨论】:

      猜你喜欢
      • 2020-10-31
      • 2021-12-24
      • 2019-09-16
      • 1970-01-01
      • 2021-08-06
      • 2020-02-27
      • 2021-08-24
      • 2016-05-15
      • 2020-02-24
      相关资源
      最近更新 更多