拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 XMLHttpRequest已被CORS策略阻止:预检回应中的Access-Control-Allow-Headers不允许请求标头栏位内容型别

XMLHttpRequest已被CORS策略阻止:预检回应中的Access-Control-Allow-Headers不允许请求标头栏位内容型别

白鹭 - 2022-01-23 2020 0 0

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

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

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

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

uj5u.com热心网友回复:

如果您已经在使用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);

在客户端,["*"]是一个无效的请求标头,需要洗掉。您也没有正确处理异步回应。它应该是

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)

uj5u.com热心网友回复:

我认为这是由这一行引起的,return res.status(200).json({}); 当您回应 CORS 飞行前您不应该包含 aContent-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();
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *