如何在使用ajax请求时清除cors错误?

时间:2018-08-21 05:58:23

标签: javascript node.js express cors passport.js

我正在尝试使用express-session和跨域护照进行会话。我需要以下链接的帮助 Sending credentials with cross-domain posts? Passport js fails to maintain session in cross-domain

**I am getting below error**
  

无法加载http://localhost:5000/users/login:响应   预检请求未通过访问控制检查:   响应中的“ Access-Control-Allow-Origin”标头不得为   当请求的凭据模式为“包括”时,使用通配符“ *”。起源   因此,不允许访问“ http://localhost:3000”。的   XMLHttpRequest发起的请求的凭据模式为   由withCredentials属性控制。

这是我的整个代码 https://github.com/naveennsit/Cors

客户端index.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}`);
})

app.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;

controller.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)
        }

    },

}

passport.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插件,但仍然收到相同的错误

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用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}));

答案 1 :(得分:0)

您几乎可以解决它。您需要在Access-Control-Allow-Origin标头值中发送实际允许的主机,而不是*

如果要允许所有起源,则可以在CORS中间件中为req.headers.origin标头值包含Access-Control-Allow-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();
});