测试环境、开发环境 (vue2.9 )
需求: vue web页面axios.get可以跨域访问http://192.168.10.30:8143/api/puppet api
动作:
- index.js 中增加proxyTable: 字段
2.vue文件中get(‘绝对路径‘)使用绝对路径,仅用uri无效
index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api/puppet': {
target: `http://192.168.10.30:8143/api/puppet`,
changeOrigin: true,
//pathRewrite: { 路径转换时才须定义次选项如:/api 转/bpi
// '^/api/puppet' : '/bpi'
//}
}
},
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8087, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
useEslint: true,
showEslintErrorsInOverlay: false,
devtool: 'cheap-module-eval-source-map',
cacheBusting: true,
cssSourceMap: true
},
vue 文件中
pulldata() {
this.axios.get("http://127.0.0.1:8087/api/puppet")
.then(function (response) {
console.log(9099)
console.log(response);
})
},
线上环境、生产环境
注意事项:
在跨域的情况下,跨域共享标准规范要求先用 OPTIONS 方法发起预检请求(preflight request),获知服务端是否允许该跨域请求。服务器确认允许之后,才发起实际的 HTTP 请求,所以后端服务器或者代理服务器必须支持options请求返回204,即可支持跨域请求
1.通过nginx代理实现
server {
listen 8087;
server_name _;
index index.html;
root /opt/dist;
location /api/puppet/ {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'OPTIONS, GET, POST, PUT, DELETE, UPDATE';
add_header Content-Type 'application/json; charset=utf-8';
add_header Access-Control-Allow-Headers 'Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With';
return 204;
}
proxy_pass http://1.9.1.3:8143;
}
location / {
root /opt/dist;
try_files $uri $uri/ /index.html;
expires 30d;
}
}
2.设置允许跨域响应头
origin := c.Request.Header.Get("origin") //请求头部
if len(origin) == 0 {
origin = c.Request.Header.Get("Origin")
}
//接收客户端发送的origin (重要!)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
//允许客户端传递校验信息比如 cookie (重要)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
//服务器支持的所有跨域请求的方法
c.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
// 设置预验请求有效期为 86400 秒
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()