前言:javascript
devServer:{ contentBase:'./', proxy:{ // 当你请求是以/api开头的时候,则我帮你代理访问到http://localhost:3000 // 例如: // /api/users http://localhost:3000/api/users // 咱们真是服务器接口是没有/api的 "/api":{ target:"http://localhost:3000", pathRewrite:{"^/api":""} } } }
用代理, 首先你得有一个标识, 告诉他你这个链接要用代理. 否则的话, 可能你的 html, css, js这些静态资源都跑去代理. 因此咱们只要接口用代理, 静态文件用本地./api’: {}, 就是告诉node, 我接口只要是’/api’开头的才用代理.因此你的接口就要这么写 /api/xx/xx. 最后代理的路径就是 http://xxx.xx.com/api/xx/xx.但是不对啊, 我正确的接口路径里面没有/api啊. 因此就须要 pathRewrite,用”^/api”:”, 把’/api’去掉, 这样既能有正确标识, 又能在请求接口的时候去掉api.css
做用:html
一、解决开发环境的跨域问题(不用在去配置nginx和host)java
二、若是你有单独的后端开发服务器 API,而且但愿在同域名下发送 API 请求 ,那么代理某些 URL 会颇有用。 node
用法:nginx
一、请求到 /api/xxx
如今会被代理到请求 http://localhost:3000/api/xxx
, 例如 /api/user
如今会被代理到请求 http://localhost:3000/api/user
后端
mmodule.exports = { //... devServer: { proxy: { '/api': 'http://localhost:3000' } } };
二、若是你想要代码多个路径代理到同一个target下, 你可使用由一个或多个「具备 context 属性的对象」构成的数组:api
module.exports = { //... devServer: { proxy: [{ context: ['/auth', '/api'], target: 'http://localhost:3000', }] } };
三、若是你不想始终传递 /api ,则须要重写路径:跨域
module.exports = { //... devServer: { proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {'^/api' : ''} } } } };
请求到 /api/xxx 如今会被代理到请求 http://localhost:3000/xxx
, 例如 /api/user 如今会被代理到请求 http://localhost:3000/user
数组
四、默认状况下,不接受运行在 HTTPS 上,且使用了无效证书的后端服务器。若是你想要接受,只要设置 secure: false
就行。修改配置以下:
module.exports = { //... devServer: { proxy: { '/api': { target: 'https://other-server.example.com', secure: false } } } };
五、有时你不想代理全部的请求。能够基于一个函数的返回值绕过代理。在函数中你能够访问请求体、响应体和代理选项。必须返回 false 或路径,来跳过代理请求。例如:对于浏览器请求,你想要提供一个 HTML 页面,可是对于 API 请求则保持代理。你能够这样作:
module.exports = { //... devServer: { proxy: { '/api': { target: 'http://localhost:3000', bypass: function(req, res, proxyOptions) { if (req.headers.accept.indexOf('html') !== -1) { console.log('Skipping proxy for browser request.'); return '/index.html'; } } } } } };
解决跨域原理
上面的参数列表中有一个changeOrigin
参数, 是一个布尔值, 设置为true, 本地就会虚拟一个服务器接收你的请求并代你发送该请求
module.exports = { //... devServer: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, } } } };