如何使用 axios 通过 webpack devlopment 服务器向远程服务器上的 API 发送请求 [英] How to send request to an API on remote server via webpack devlopment server using axios

查看:80
本文介绍了如何使用 axios 通过 webpack devlopment 服务器向远程服务器上的 API 发送请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从支持 REST API 的远程服务器获取一些数据.我正在使用 axios 和 web-dev-server.我的前端正在发送请求,我同时使用了 Firefox 和 chrome 来打开我的前端.但是,每次我尝试提出请求时,都会遇到 cors 错误.此外,我不想在我的服务器上进行任何更改.firefox 和 chrome 正在发送此标头.

<预>接受:*/*接受编码:gzip,放气接受语言:en-US,en;q=0.5连接:保持连接主机:my.ip.to.host:端口来源:http://localhost:3000引用者:http://localhost:3000/login用户代理:Mozilla/5.0 (X11; Ubuntu; Linu...) Gecko/20100101 Firefox/67.0

我尝试在没有 web-dev-server 的在线平台上运行我的简单请求代码,并且在那里运行得非常好.

这是我的代码<预>//********** 我的请求*********返回 axios.get('http://my.ip.to.host:port/api/用户/登录', {标题:{接受:'/'}}).then(功能(响应){控制台日志(响应);返回用户";}).catch(函数(错误){控制台日志(错误);返回错误";});//********************************

<预>//*****webpack.config.js********var HtmlWebpackPlugin = require('html-webpack-plugin');require('babel-polyfill');模块.出口 = {模式:'发展',条目:['babel-polyfill','./src'],解决: {扩展名:['.js','.jsx']},模块: {规则: [{测试:/.jsx?$/,loader: 'babel-loader'}]},插件: [新的 HtmlWebpackPlugin({模板:'./src/index.html'})],开发服务器:{historyApiFallback: 真,端口:3000},外部:{//全局应用配置对象配置:JSON.stringify({apiUrl: 'http://localhost:4000',checkLogin: 'http://my.ip.to.host:port/api/用户/登录'})}};

这是我遇到的错误.

<预>跨域请求被阻止:同源策略不允许读取位于 http://my.ip.to.host:port/api/User/login 的远程资源.(原因:缺少 CORS 标头Access-Control-Allow-Origin").`在此处输入代码`

解决方案

这里 Google 已经解释了 cors(跨域请求)非常好.

我通过托管代理服务器(在我托管客户端的同一本地服务器上)并通过它重定向我的所有单页应用程序请求来解决此问题.

首先,我在 webpack 配置文件的 devsever key 中创建了一个代理设置,如下所示.

<预><代码>开发服务器:{代理人: {//abc 是我后端的 REST API 请求端点'/abc':{//target 是你的代理服务器所在的地方目标:'http://localhost:5000',安全:'假'},//xyz 是我后端的 REST API 请求端点'/xyz':{//target 是你的代理服务器所在的地方目标:'http://localhost:5000',安全:'假'}},......//其余设置}

那么,对于通过我的客户端进行的特定操作调用,我会像这样向我的后端发出请求.

<预><代码>公理.get('/startAppkey', { withCredentials: true })//withCredential 允许传递 cookie 和会话 ID.如果您不想创建会话,则可以避免这种情况..then((响应) => {//用响应做事}).catch(函数(){//做东西});

我们的客户已准备就绪.现在是代理服务器的时间.先安装http-proxy-middleware,像这样

<预><代码>须藤 npm i --save http-proxy-middleware//它也可以在纱线上使用

那么,在这里设置代理服务器只需几行代码.

<预>import * as express from 'express';//使用 express 来支持我的中间件从 'http-proxy-middleware' 导入 * 作为代理;const app = express();//路径/abc 和/xyz 应该与你在 webpack 配置文件中声明的相同app.use('/abc', proxy({ target: 'http://your/backend/api/endpoint'}));app.use('/xyz', proxy({ target: 'http://your/backend/api/endpoint'}));//到这里你就完成了.

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. 


这篇关于如何使用 axios 通过 webpack devlopment 服务器向远程服务器上的 API 发送请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆