使用官网推荐的跨域方式实现跨域——安装依赖http-proxy-middleware
1 2 3
| npm install http-proxy-middleware
yarn add http-proxy-middleware
|
新建setupProxy.js,在里面配置如下
1 2 3 4 5 6 7 8 9 10 11 12 13
| const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', proxy.createProxyMiddleware({ target: 'https://apis.map.qq.com/ws/geocoder/v1/', changeOrigin: true, pathRewrite: { '^/api': '' } }) ); };
|
需要注意的是,官网的demo如下
1 2 3 4 5 6 7 8 9 10 11
| const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true, }) ); };
|
运行就会报proxy is not a funciton的错误,可能以为官网的例子写得比较早,后面依赖更新了,不适用了,修改成上面的正确例子就行了
最后使用axios请求就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| getData = () => { axios.get("/api", { params: this.state.data }) .then(res => { let data = res.data console.log(data.result.address) this.setState( { addressArr: res.data.result.address }) console.log(this.state.addressArr) }) .catch(err => { console.log("catch", err); });
};
|