如何在客户端React(javascript)中设置用于axios或提取的porxy。
尝试了很多解决方案,但都无法加载api。 疲倦的axios-proxy-fix也是如此。
进行确认-该API可与Chrome CORS和Switchy代理扩展一起使用。
没有Webpack-
给出ip并托管例如x.x.x.x:xx
{
"name": "testapp",
"version": "0.1.0",
"private": true,
"proxy": "http://X.X.X.X:X",
"devDependencies": {
"bootstrap": "^4.0.0-alpha.6",
"jest": "^19.0.2",
"material-ui": "^0.17.4",
"node-sass": "^4.5.0",
"nodemon": "^1.11.0",
"npm-run-all": "^v4.0.1",
"pushstate-server": "^3.0.0",
"react-cookie": "^1.0.5",
"react-scripts": "0.9.0",
"redux": "^3.6.0",
"jquery": "^3.1.1",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"dependencies": {
"axios": "^0.18.0",
"axios-proxy-fix": "^0.16.3",
"es6-promise": "^4.1.0",
"isomorphic-fetch": "^2.2.1",
"react-addons-css-transition-group": "^15.4.2",
"react-addons-transition-group": "^15.4.2",
"reactstrap": "^4.2.0",
"tracer": "^0.8.7",
"treeview-react-bootstrap": "^0.4.6",
"tunnel": "0.0.6"
},
"scripts": {
"build-css": "node-sass src/ -o src/",
"watch-css": "nodemon -e scss -x \"npm run build-css\"",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
和组件
import axios from 'axios-proxy-fix';
//OR
import axios from 'axios';
/*********
The not writing rest of component stuff only axios part
***********/
axios({
method: 'get',
url: '/api/some-endpoint',
baseURL: "the-base-url",
headers: {
'httpAgent': 'new http.Agent({ keepAlive: true })',
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Proxy-Connection": "keep-alive"
},
proxy: {
host: 'X.X.X.X',
port: '80'
}
})
.then(res => {
alert("ajax-respo-world");
const posts = res.data.data;
this.setState({ posts });
}).catch(err => console.log("ajax-err", err))
}
答案 0 :(得分:0)
我相信上面的对话可以很清楚地得出一个答案,即可以通过 server 而不是通过 client 进行具有代理的api调用。