简体   繁体   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

I am having issues creating new users from the form due to CORS.由于 CORS,我在从表单创建新用户时遇到问题。 I was able to last week in this app but not sure what is missing from my server (methods, origin, headers, etc.)or my API call.我上周可以在这个应用程序中使用,但不确定我的服务器(方法、来源、标头等)或我的 API 调用中缺少什么。

Here is what is suggested in the issues part of the console:以下是控制台问题部分的建议:

To fix this issue, include the additional request headers you want to use in the Access-Control-Allow-Headers response header of the associated preflight request.要解决此问题,请在关联的预检请求的 Access-Control-Allow-Headers 响应 header 中包含要使用的其他请求标头。 1 request Request Status Preflight Request Disallowed Request Header new_user blocked new_user content-type 1 请求请求状态预检请求不允许请求 Header new_user 阻止 new_user 内容类型

Here is the server code:这是服务器代码:

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

Here are the routes:以下是路线:

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

Here is the client (form code):这是客户端(表单代码):

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

I've done a bit of research and not sure if I should make a proxy, use a plugin, etc, but I could use the extra eyes.我做了一些研究,不确定是否应该制作代理,使用插件等,但我可以使用额外的眼睛。 Thanks all!谢谢大家!

If you're already using the cors middleware , you don't need to manually handle OPTIONS requests, itdoes that for you .如果您已经在使用cors 中间件,则无需手动处理OPTIONS请求,它会为您完成

Remove this section...删除此部分...

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

You should also register the cors middleware before your routes, along with your other middleware.您还应该在路由之前注册 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);

On the client-side, ["*"] is an invalid request header and needs to be removed.在客户端, ["*"]是一个无效请求 header,需要删除。 You're also not handling the async response correctly.您也没有正确处理异步响应。 It should be它应该是

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)

I think that it is caused by this line return res.status(200).json({});我认为这是由这一行引起的return res.status(200).json({}); When you respond to the CORS pre-flight you are not supposed to include a Content-Type and setting the return type to JSON probably does exactly this.当您在飞行前响应 CORS 时,您不应该包含Content-Type并将返回类型设置为 JSON 可能正是这样做的。

Try尝试

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.

相关问题 被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型 - blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response 根据 CORS 预检响应中的 header 'Access-Control-Allow-Headers' 不允许使用 'content-type' - ‘content-type’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response 被 CORS 阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求 header 字段授权 - Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response Slack 传入 webhook:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-type - Slack incoming webhook: Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response React.js + PHP/Apache:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型 - React.js + PHP/Apache: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response CI和Angular4:在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段的内容类型 - CI and Angular4 : Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response Safari的XMLHttpRequest(POST)失败,“ Access-Control-Allow-Headers不允许请求标头字段Content-Type” - Safari fails XMLHttpRequest (POST) with ' Request header field Content-Type is not allowed by Access-Control-Allow-Headers' CORS:飞行前响应中Access-Control-Allow-Headers不允许Content-Type - CORS: Content-Type is not allowed by Access-Control-Allow-Headers in preflight response 预检响应中的 Access-Control-Allow-Headers 不允许 XMLHttpRequest 请求标头字段 postman-token - XMLHttpRequest Request header field postman-token is not allowed by Access-Control-Allow-Headers in preflight response XMLHttpRequest无法加载。 飞行前响应中Access-Control-Allow-Headers不允许使用请求标头字段密码 - XMLHttpRequest cannot load. Request header field password is not allowed by Access-Control-Allow-Headers in preflight response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM