如何使用 axios 通过 webpack 开发服务器向远程服务器上的 API 发送请求
How to send request to an API on remote server via webpack devlopment server using axios
我想从支持 REST 的远程服务器获取一些数据 API。
我正在使用 axios 和 web-dev-server。我的前端正在发送请求,我同时使用 firefox 和 chrome 打开我的前端。
但是,每次我尝试发出请求时,都会遇到 cors 错误。
此外,我不想在我的服务器上进行任何更改。
firefox 和 chrome 正在发送这个 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
我已经尝试 运行 我在没有 web-dev-server 的在线平台上的简单请求代码,并且 运行 完全没问题。
这是我的代码
//********** 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'
})
}
};
这是我遇到的错误。
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`
您需要在 axios 配置中将 withCredentials
设置为 true
。 Cors Setting
let HttpInterceptor = axios.create({
headers: {
Accept: "*/*"
}
});
HttpInterceptor.interceptors.request.use(
function(config) {
config.withCredentials = true; // To enable CORS
return config;
},
function(error) {
return promise.reject(error);
}
);
//********** Your request*********
return HttpInterceptor
.get('http://my.ip.to.host:port/api/User/login')
.then(function(response) {
console.log(response);
return 'user';
})
.catch(function(error) {
console.log(error);
return 'err';
});
这里Google很好地解释了cors(Cross-origin requests)。
我通过托管代理服务器(在我托管客户端的同一本地服务器上)并通过它重定向我所有的单页应用程序请求来解决这个问题。
首先,我在 webpack 配置文件的 devsever 键中创建了一个代理设置,就像这样。
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
}
那么,
对于通过我的客户端的特定操作调用,我像这样向我的后端发出请求。
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
});
我们的客户已经准备就绪。
现在是代理服务器的时候了。
首先安装http-proxy-middleware,像这样。
sudo npm i --save http-proxy-middleware
//it is also avilable on yarn
那么,
在这里设置代理服务器是几行代码。
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.
我想从支持 REST 的远程服务器获取一些数据 API。 我正在使用 axios 和 web-dev-server。我的前端正在发送请求,我同时使用 firefox 和 chrome 打开我的前端。 但是,每次我尝试发出请求时,都会遇到 cors 错误。 此外,我不想在我的服务器上进行任何更改。 firefox 和 chrome 正在发送这个 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
我已经尝试 运行 我在没有 web-dev-server 的在线平台上的简单请求代码,并且 运行 完全没问题。
这是我的代码
//********** 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' }) } };
这是我遇到的错误。
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`
您需要在 axios 配置中将 withCredentials
设置为 true
。 Cors Setting
let HttpInterceptor = axios.create({
headers: {
Accept: "*/*"
}
});
HttpInterceptor.interceptors.request.use(
function(config) {
config.withCredentials = true; // To enable CORS
return config;
},
function(error) {
return promise.reject(error);
}
);
//********** Your request*********
return HttpInterceptor
.get('http://my.ip.to.host:port/api/User/login')
.then(function(response) {
console.log(response);
return 'user';
})
.catch(function(error) {
console.log(error);
return 'err';
});
这里Google很好地解释了cors(Cross-origin requests)。
我通过托管代理服务器(在我托管客户端的同一本地服务器上)并通过它重定向我所有的单页应用程序请求来解决这个问题。
首先,我在 webpack 配置文件的 devsever 键中创建了一个代理设置,就像这样。
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
}
那么, 对于通过我的客户端的特定操作调用,我像这样向我的后端发出请求。
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
});
我们的客户已经准备就绪。 现在是代理服务器的时候了。 首先安装http-proxy-middleware,像这样。
sudo npm i --save http-proxy-middleware
//it is also avilable on yarn
那么, 在这里设置代理服务器是几行代码。
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.