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

相關文章
相關標籤/搜索