前言
在现在前后端分离开发模式中,API接口成了,连接前后台的重要一步, 而开发中前台请求受同源策略的限制,会出现跨域的问题,有很多解决跨域的方法,其实每个公司都会使用统一的一种, 我们使用的vue框架,所以直接配置就行。
但还有些jquery项目需要调试。
package.json
利用express和http-proxy-middleware来写,依赖如下
{
"name": "expressProxy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"connect-timeout": "^1.9.0",
"express": "^4.16.4",
"http-proxy-middleware": "^0.19.1"
}
}
复制代码
index.js
/*
express + http-proxy-middleware 代理请求
*/
const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();
// 本服务端口
const PORT = 9527
// cookie写入地址
const cookieUrl = '127.0.0.1'
// PORT 服务端口
const kandao = {
target : 'http://125.44.97.88:8900',
changeOrigin: true,
cookieDomainRewrite: {
"*": cookieUrl // 把相应的 cookie 域都设置成 localhost
},
ws: true,
withCredentials: true,
}
// 超时时间
const TIME_OUT = 30 * 1e3;
// 设置端口
// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Access-Control-Allow-Headers,Authorization,Origin,Accept,Power-By,x-token-id");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
res.header("accept",'image/webp,image/apng,image/*,*/*;q=0.8')
// res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use((req, res, next) => {
if (!req.timedout) next();
});
// 看到代理
app.use(proxy('/cms', { ...kandao }));
// 监听端口
app.listen(PORT, () => {
console.log(`启动代理服务器=> http://127.0.0.1:${PORT}`);
});
复制代码
执行
npm run dev
复制代码
前台请求
let url = 'http://127.0.0.1:9527'
$.ajax(
{
url,
// 如果请求需自动带上cookie
type: 'GET',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success () {}
}
)
复制代码