# 跨域

下面将介绍俩种解决跨域的方法,一种从前端,一种从后端(node)去解决

# 后端解决方法

# express中的解决方法

在app.js中加入以下代码

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});
1
2
3
4
5
6
7
8

# koa中的解决方法

  • 安装koa-cors

  • app.js中加入

const cors = require('koa-cors');
app.use(cors());
1
2

# 前端解决方法

以下是在vue中的解决方法 配置反向代理

devServer: {
        proxy: {
            '': {
                target: 'http://localhost:3000', 
                changeOrigin: true,
                ws: true
 
            }
        }
    },
1
2
3
4
5
6
7
8
9
10

以上仅仅是在开发环境中,在生产环境中会报路径404错误,因此还需要配置nginx

location / {
proxy_set_header   Host             $host;
proxy_set_header   x-forwarded-for  $remote_addr;
proxy_set_header   X-Real-IP        $remote_addr;
proxy_pass http://127.0.0.1:3000; // 接口地址,如果在同一个服务器上,可以直接这样写
}    
1
2
3
4
5
6
Last Updated: 4/16/2019, 4:43:02 PM