第一步:在package.json里面加proxy
网络异常,图片无法展示
|
这个proxy必须要是String类型,并且是本地需要跨域的路径
"proxy": "http://localhost:3000" 复制代码
第二步: 设置setupProxy.js, 设置跨域路径设置
在src下面,新建setupProxy.js,代码如下
const {createProxyMiddleware} = require("http-proxy-middleware"); module.exports = function (app) { // app.use( // createProxyMiddleware("/apis", { // target: "https://xxx.xxx.cn", // 需要跨域的网址 // changeOrigin: true, //跨域 // }) // ) app.use( createProxyMiddleware("/api", { // 这个/api,就是识别的请求路径拼接,告诉请求,当什么请求时,需要用到这里跨域 target: "https://c.m.163.com/ug", changeOrigin: true, //跨域 }) ) } 复制代码
然后就ok啦~
可以跨域请求鸟
import React from 'react' import ReactDom from 'react-dom' import axios from 'axios' (async function() { const url = '/api/wuhan/app/data/list-total?t=' + new Date().getTime() const res = await axios.get(url) console.log(res) }()) 复制代码
网络异常,图片无法展示
|
\
第二步有一个深坑 (React中代理异常Proxy is not a function)
问题: 官方给出的proxy配置文档 (www.html.cn/create-reac…)
如下
const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use(proxy('/api', { target: 'http://xxx.xxx.com' })); }; 复制代码
启动报错如下
proxy is not a function error Command failed with exit code 1. 复制代码
解决方案:查询npm的http-proxy-middleware,发现1.x做了较大改动。
文档(www.npmjs.com/package/htt…)
正确写法:
const {createProxyMiddleware} = require('http-proxy-middleware'); module.exports = function(app) { app.use(createProxyMiddleware('/api', { target: 'http://localhost:5000/' })); }; // 或者 const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use(proxy.createProxyMiddleware('/api', { target: 'http://localhost:5000/' })); }; 复制代码
片尾: http.js配置
import axios from 'axios' import qs from 'qs' axios.defaults.baseURL = 'https://c.m.163.com/ug/' axios.defaults.withCredentials = true axios.defaults.timeout = 100000 let http = { post: '', get: '' } http.post = (api, data) => { const params = qs.stringify(data) return new Promise((resolve, reject) => { axios.post(api, params).then(r => { resolve(r) }).catch(e => { reject(e) }) }) } http.get = (api, data) => { const params = qs.stringify(data) return new Promise((resolve, reject) =>{ axios.get(api, params).then(r => { resolve(r) }).catch(e => { reject(e) }) }) } export default http