Fork me on GitHub

node下的跨域传递cookie

研究背景:

最近有一位朋友找工作,需要面试,涉及到面试就涉及面试题,于是我想起来鄙人之前面试被问到的一个跨域传递cookie的问题。搜索了相关资料,但自己不敲一下肯定是不足以让人信服的。

我用node框架express实现后端代码。

前端用node的anywhere跑一个服务器。

设置的部分有后端express的路由,需要允许前端跨域,且只能允许前端特定的地址跨域,而不能是‘*’,设置如下

app.all('*', function(req, res, next) {
  console.log(req.headers.origin,'http://10.168.8.63:8000');
    res.header("Access-Control-Allow-Origin", req.headers.origin); //需要显示设置来源,不能使用‘*’
  
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials",true); //需要加上这个
    next();
});

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/upload', uploadRouter);
app.use('/formdata', formdataRouter);

前端使用的axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script type="text/javascript">
    document.cookie = "name=7878";
    document.cookie = "eee=7878";
    axios({
            url: 'http://localhost:3000/users',
            params: {},
            method: 'post',
            data: {
                'name': 1, 
                'jobId': 2,
                'department': 3,
            },
            withCredentials: true // 需要设置为true
        })
        .then(function(response) {
            console.log(response, document.cookie);
        })
        .catch(function(error) {
            console.log(error.response, 454545);
            alert(error.response.data.error)
        });

上面绿色是需要注意的,配置了上述三点才能实现跨域传递cookie。另外有一点:这种方式的下后端设置的cookie不会出现在浏览器的application里面。

posted @ 2019-04-08 14:18  我站在山顶上  阅读(869)  评论(0编辑  收藏  举报