node下的跨域传递cookie

研究背景:javascript

最近有一位朋友找工做,须要面试,涉及到面试就涉及面试题,因而我想起来鄙人以前面试被问到的一个跨域传递cookie的问题。搜索了相关资料,但本身不敲一下确定是不足以让人信服的。前端

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

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

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

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里面。express

相关文章
相关标签/搜索