使用webpack服务器代理设置绕过跨域AJAX请求

Circumventing cross domain AJAX request with webpack server proxy setting

本文关键字:AJAX 请求 webpack 服务器 代理 设置 使用      更新时间:2023-09-26

我们如何编写一个webpack配置,使我们能够在没有CORS设置/启用的www.example.com/api/books域/url上执行成功的AJAX (get)请求?

基于这个问题。

我从域得到的错误是:No 'Access-Control-Allow-Origin' header is present on the requested resource.

我试图添加这个对象到我的webpack.base.conf.js文件:

    proxy: {
       '/api': {
         target: 'http://www.example.com',
         secure: false
       }
     }

并改编了我的HTTP根url:

Vue.http.options.root = 'http://www.example.com/api/'

:

Vue.http.options.root = '/api/'

但是在我的AJAX请求期间似乎没有考虑到它:

GET http://localhost:8080/api/public/v1.0/lists/movies/in_theaters.json (Not Found)

我找到问题了。

我的Webpack配置通过一个index.js文件加载它的配置,该文件包含所有的module.exports = { }

在那里我发现了一个proxyTable空对象,我在其中添加:

dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      // proxy all requests starting with /api to jsonplaceholder
      '/api': {
        target: 'http://api.example.com',
        changeOrigin: true,
      }
    }
},

然后我做了我的AJAX请求相对/api/whatever路径,他们是反向代理,所以服务器接受他们。