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

1、nodejs端

  • 安装cors:npm i cors -s

  • 配置:

    const cors = require('cors');
    
    // 初始化 express 实例
    var app = express();
    
    var corsOptions = {
        origin: 'http://localhost:8080',
        credentials: true,
        maxAge: '1728000'
    }
    
    app.use(cors(corsOptions))
    

2、前端

2.1、原生js

var xhr = new XMLHttpRequest()
xhr.open('GET','http://localhost:8080')
xhr.withCredentials = true
xhr.onload = onLoadHandler
xhr.send()

2.2、jquery

$.ajax({
    url: `http://localhost:8001/api/blog/list`,
    type: 'GET',
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    headers: {
        'content-type': 'application/json'
    },
    data: {},
    success: function (res) {
        console.log(res);
    },
    error: function (err) {
        console.log(err)
    }
})

2.3、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.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
})

解决nodejs中cors跨域cookie和session失效的问题
http://localhost:8090//archives/jie-jue-nodejs-zhong-cros-kua-yu-cookie-he-session-shi-xiao-de-wen-ti
作者
龟龟
发布于
2022年12月14日
更新于
2024年08月28日
许可协议