I want to fetch some data from my remote server supporting REST API. I am using axios and web-dev-server. My frontend is sending request and I have used both firefox and chrome to open my frontend. However every time I tries to make request I encounter cors error. Also I don't want to make any changes on my server. The firefox and chrome are sending this header.
Accept:*/* Accept-Encoding:gzip, deflate Accept-Language :en-US,en;q=0.5 Connection:keep-alive Host:my.ip.to.host:port Origin:http://localhost:3000 Referer:http://localhost:3000/login User-Agent:Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/67.0
I have tried to run my simple request code on an online platform without web-dev-server and there it runs perfectly fine.
Here is my code
//********** my request********* return axios .get('http://my.ip.to.host:port/api/User/login', { headers: { Accept: '/' } }) .then(function(response) { console.log(response); return 'user'; }) .catch(function(error) { console.log(error); return 'err'; }); //*****************************
//*****webpack.config.js******** var HtmlWebpackPlugin = require('html-webpack-plugin'); require('babel-polyfill'); module.exports = { mode: 'development', entry: [ 'babel-polyfill', './src' ], resolve: { extensions: [ '.js', '.jsx' ] }, module: { rules: [ { test: /.jsx?$/, loader: 'babel-loader' } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], devServer: { historyApiFallback: true, port: 3000 }, externals: { // global app config object config: JSON.stringify({ apiUrl: 'http://localhost:4000', checkLogin: 'http://my.ip.to.host:port/api/User/login' }) } };
Here is the error I am getting.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my.ip.to.host:port/api/User/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).`enter code here`
Here Google has explained the cors(Cross-origin requests) very nicely.
I have worked around this by hosting a proxy server(on the same local server where I am hosting my client) and redirecting all my single page app request via that.
First of all, I created a proxy setting in devsever key of webpack config file, like this.
devServer: {
proxy: {
//abc is REST API request endpoint on my backend
'/abc': {
//target is where your proxy server is hosted
target: 'http://localhost:5000',
secure: 'false'
},
//xyz is REST API request endpoint on my backend
'/xyz': {
//target is where your proxy server is hosted
target: 'http://localhost:5000',
secure: 'false'
}
},......// rest of the setting
}
Then, For a particular invocation of a action via my client I make request to my backend like this.
axios
.get('/startAppkey', { withCredentials: true })// withCredential enables passing of cookies and session id. If you dont want to creat session you can avoid this.
.then((response) => {
// do stuff with response
})
.catch(function() {
//do stuff
});
Our client is all set. Now time for proxy server. First install http-proxy-middleware,Like this.
sudo npm i --save http-proxy-middleware
//it is also avilable on yarn
then, To setup proxy server here is few lines of code.
import * as express from 'express'; // using express to support my middleware import * as proxy from 'http-proxy-middleware'; const app = express(); // the path /abc and /xyz should be same as you have declared in in webpack config file app.use('/abc', proxy({ target: 'http://your/backend/api/endpoint'})); app.use('/xyz', proxy({ target: 'http://your/backend/api/endpoint'})); //that's it you are done here.