解决nodejs中cros跨域cookie和session失效的问题

nodejs端

const cors = require('cors');
var app=express();

var corsOptions = {
  origin: 'http://localhost:8080',
  credentials: true,
  maxAge: '1728000'
  //这一项是为了跨域专门设置的
}
app.use(cors(corsOptions))

前端

1.vue-resource

this.$http.get('getlogin',{ credentials: true }).then(res => {
                    console.log(res)
                })
 this.$http.post('postlogin',{userInfo: $('.form-signin').serialize()},{ credentials: true }).then(res => {
                    console.log(res)
                    if(res.body.status != 200) {
                        console.log('登录失败')
                    }else {
                        console.log('登录成功')
                    }
                })

2.原生js中api

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/api');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send()

3.jquery中

$.ajax({
            url: "http://localhost:8080/orders",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                render(data);
            }
 });

4.axios

const service = axios.create({
  baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
  timeout: 5000, // 请求的超时时间
  //设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
  // headers: {  
    // "Content-Type": "application/x-www-form-urlencoded"
  // },
  withCredentials: true // 允许携带cookie
})

https://www.cnblogs.com/lijinwen/p/8012547.html

转载于:https://my.oschina.net/u/3937325/blog/1925486

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值