npm install axios
import axios from 'axios';
在项目的package.json文件中添加:
"proxy":"http://localhost:5000/"
使用的地方直接使用
- import axios from 'axios';
-
-
- click = () => {
- axios.get('http://localhost:3000/ctiy').then(
- response => {
- console.log('获取数据成功',response.data)
- },
- error => {
- console.log('获取数据失败',error)
-
- }
- )
- }
- setupProxy.js内容
-
- const proxy = require('http-proxy-middleware');
-
- module.exports = function(app) {
- app.use(
- proxy('/api11', {
- target: "http://localhost:5000",
- //target配置成'http://localhost:5000'意味着只要发现/api11前缀的请求,
- //就自动转发到'http://localhost:5000'这个地址,
- //并且通过配置pathRewrite: {'^/api11': ''}把添加了/api11的请求地址还原回去
- changeOrigin: true,
- // 控制服务器收到的请求头中的Host的值 如果设置为true,服务器不会知道真实的请求地址,
- //只会知道代理的地址,如果设置为false,服务器会知道真正请求的地址
- pathRewrite: {'^/api11': ''}
- // 重写请求路径 这个必须要加,如果不加 服务器端收到的请求地址是 /api/url 请求地址就不对了
- }),
- proxy('/banzhuan', {
- target: "http://localhost:5001",
- changeOrigin: true,
- pathRewrite: {'^/banzhuan': ''}
- })
- )
- }
- setupProxy.js内容
-
- const {createProxyMiddleware} = require('http-proxy-middleware');
-
- module.exports = function (App) {
- App.use(
- createProxyMiddleware('/api11', {
- target: 'http://localhost:5000',
- changeOrigin: true,
- pathRewrite:{'^/api11':''}
- }
- ),
- createProxyMiddleware('/banzhuan', {
- target: 'http://localhost:5001',
- changeOrigin: true,
- pathRewrite:{'^/banzhuan':''}
- }
- )
- )
- }
页面使用
- 使用页面内容
- click = () => {
- axios.get('http://localhost:3000/api11/ctiy').then(
- response => { console.log('请求成功', response) },
- error => {console.log('请求失败,',error)}
- )
- }
- clickCase = () => {
- axios.get('http://localhost:3000/banzhuan/cars').then(
- response => { console.log('小汽车请求成功', response) },
- error =>{console.log('失败',error)}
- )
- }