使用 webpack 服务器代理设置绕过跨域 AJAX 请求
Circumventing cross domain AJAX request with webpack server proxy setting
我们如何编写一个 webpack 配置,使我们能够在没有 CORS setup/enabled 的 www.example.com/api/books
domain/url 上执行成功的 AJAX (get) 请求]?
基于this question。
我从域中得到的错误是: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,
}
}
},
然后我向相对 /api/whatever
路径发出 AJAX 请求,它们被反向代理,因此服务器接受它们。
我们如何编写一个 webpack 配置,使我们能够在没有 CORS setup/enabled 的 www.example.com/api/books
domain/url 上执行成功的 AJAX (get) 请求]?
基于this question。
我从域中得到的错误是: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,
}
}
},
然后我向相对 /api/whatever
路径发出 AJAX 请求,它们被反向代理,因此服务器接受它们。