繁体   English   中英

XMLHttpRequest 已被 CORS 策略阻止:请求 header 字段内容类型在预检响应中不允许访问控制允许标头

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

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

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

要解决此问题,请在关联的预检请求的 Access-Control-Allow-Headers 响应 header 中包含要使用的其他请求标头。 1 请求请求状态预检请求不允许请求 Header new_user 阻止 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))

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

如果您已经在使用cors 中间件,则无需手动处理OPTIONS请求,它会为您完成

删除此部分...

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

在客户端, ["*"]是一个无效请求 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)

我认为这是由这一行引起的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM