Beego和Vue的前后端分离跨域问题处理

VUE封装的请求头(注意请求头,跨域要用到)

路径 utils/mereq.js

import request from '@/utils/request'
import qs from 'qs'

export default{
    get(url,params){
        return request({
            method:'get',
            url,
            params,
            headers:{
                'X-Requested-With':'XMLHttpRequest',
                'withCredentials':true,
            }
        })
    },
    post(url,data){
        return request({
            method:'post',
            url,
            data:qs.stringify(data),
            headers:{
                'X-Requested-With':'XMLHttpRequest',
                'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
            }
        })
    },
    postJson(url,data){
        return request({
            method:'post',
            url,
            data
        })
    }
}

Beego的跨域处理

路径 routers/touter.go

新增依赖

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/plugins/cors"
)

init函数初始化跨域问题

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", "withCredentials"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

注意AllowHeaders里面的请求头对应VUE封装的get\post\post方法中的headers中的请求头

上一篇:beego启动找不到conf的原因


下一篇:jQuery事件(1)