zoukankan      html  css  js  c++  java
  • 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里面。

  • 相关阅读:
    使用ssh公钥实现ssh免密码登录
    如何定义领域模型(概念模型)
    17.python字符编码检测——chardet
    21.python对象的浅拷贝和深拷贝
    15.序列化python对象
    18.python的打包和发布
    16.python的网络编程
    13.python的文件操作
    linux下python、django框架的配置
    14.python的xml操作
  • 原文地址:https://www.cnblogs.com/zhensg123/p/10670219.html
Copyright © 2011-2022 走看看