今天做Vue+beego的前后端对接遇到了跨域问题,特此记录

一、beego跨域处理

问题一:

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

解决:这个问题主要是beego没有做跨域处理

beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

问题二:

Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight response.

Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.

beego设置的头部信息不满足前端跨域条件,新增头部信息

beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "X-Token", "X-Requested-With"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

参数详解

AllowAllOrigins 允许全部来源

注:设置为true,则所有域名都可以访问本网站接口,可以将此配置换成为AllowOrigins:[“允许访问的域名”]
来限定特定的域名

AllowMethods :允许的请求方式

注:请求方式有GET,POST,PUT,DELETE,OPTIONS

AllowHeaders:允许的头部信息
ExposeHeaders:允许暴露的头信息
AllowCredentials:如果设置,允许共享AuthTuffic证书,如Cookie


二、Vue跨域处理

Vue使用的是Axios做跨域处理,文件目录是/src/utils/request.js,配置如下

// create an axios instance
const service = axios.create({
  baseURL: 'http://服务器ip:服务器端口', // api 的 base_url
  // baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
})

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['content-type'] = 'application/json'
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)