簡體   English   中英

如何在使用ajax請求時刪除cors錯誤?

[英]how to remove cors error while using ajax request?

我正在嘗試使用帶有跨域護照的express-session進行會話。我借助以下鏈接使用跨域帖子發送憑據? Passport js 無法在跨域中維護會話

**I am getting below error**

加載http://localhost:5000/users/login失敗:對預檢請求的響應未通過訪問控制檢查:響應中“Access-Control-Allow-Origin”標頭的值不能是通配符“ *' 當請求的憑據模式為 'include' 時。 因此,不允許訪問 Origin ' http://localhost:3000 '。 XMLHttpRequest 發起的請求的憑證模式由 withCredentials 屬性控制。

這是我的整個代碼https://github.com/naveennsit/Cors

客戶端索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="style/style.css" rel="stylesheet" type="text/css"/>
    <script src="../node_modules/jquery/dist/jquery.js"></script>
    <script src="jquery.js"></script>
</head>
<body>
<script>
    $(function () {
        $.ajax({
            url: 'http://localhost:5000/users/login',
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({id: 5}),
            dataType: 'json',
            xhrFields: {
                withCredentials: true,

            },
            crossDomain: true,
            success: function () {
                console.log('success');
            },
            error: function () {
                console.log('error')
            }
        });
    })
</script>
</body>
</html>

服務器代碼server.js

var app = require('./app');
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
    console.log(`app is running on ${PORT}`);
})

應用程序.js

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');

const morgan = require('morgan');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');



const app = express();



// Middleware
app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(cors());

app.use(cookieParser());

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
    res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
    next();
});
app.use(session({
    secret: 'secret',
    resave: false,
    domain: '.localhost:3000',
    saveUninitialized: false,
    cookie:  {
        domain: '.localhost:3000',
        maxAge: 24 * 6 * 60 * 10000
    },
}))



app.use(passport.initialize());
app.use(passport.session());

//Routes


app.use('/users', require('./routes/user.route'))


module.exports = app;

控制器.js

const passport = require('passport');


const passportConfig = require('../passport')
module.exports = {
    login: async (req, res, next) => {
        console.log(req.body);
        try {

            req.login(req.body.id, function () {
                res.json({message: "Registration successfully"});

            })
        } catch (e) {
            console.log(e)
        }

    },

}

護照.js

const passport = require('passport');
passport.serializeUser(function(id, done) {
    console.log('ddd');
//    console.log(user);
    done(null, id);
});

passport.deserializeUser(function(id, done) {
    console.log('deserializeUser');
    done(null, id);
    // db.User.findById(id, function (err, user) {
    //     done(err, user);
    // });
});

路線

const express = require('express');
const router = require('express-promise-router')();


const controller = require('../controllers/user.controller');



router.route('/login',)
    .post(controller.login)



module.exports = router;

我想在跨域中添加會話。我已經應用了 cors 插件仍然遇到相同的錯誤

最簡單的方法是使用 node.js 包cors 最簡單的用法是:

var cors = require('cors')

var app = express();

app.use(cors());

在ajax中使用withCredentials: true時,cors需要如下配置。

app.use(cors({origin: 'http://localhost:3000', credentials: true}));

你幾乎可以解決它。 您需要在Access-Control-Allow-Origin標頭值中發送實際允許的主機而不是*

如果您想允許所有來源,那么您可以在 CORS 中間件中為Access-Control-Allow-Origin標頭值包含req.headers.origin

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
    res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
    next();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM