axios跨域请求遇到的问题

个人的小demo,用vue构建前台,配合axios做ajax请求。后台服务器用node+experss搭建。遇到的几个问题做下总结:

1 node+express后台需要开通权限供前台发送ajax请求。可增加中间件:

app.use((req, res, next) => {
	// 允许的请求主机名及端口号 也可以用通配符*, 表示允许所有主机请求
	res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
	// 允许请求携带cookie 
	res.setHeader('Access-Control-Allow-Credentials', true);
    // 允许的请求方式
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // 允许的请求头
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
	next();
});


2 用axios发送请求时,后台保存了session,但是在前台每次刷新页面的时候,发现从后端请求到的session值每次都不一样。以下是axios的关于跨域cookie的说明:

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: true, // default

把默认配置withCredentials改为true,就可以允许跨域携带cookie信息了。vue的入口文件如下:

import Vue from 'vue'
import axios from 'axios'
import App from './App'
import router from './router'

axios.defaults.withCredentials=true;
Vue.prototype.$http = axios;

Vue.config.productionTip = true

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

这样每次发送ajax请求后,只要不关闭浏览器,得到的session数据都是一致的。





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值