使用 vue-cli 代理请求到单独的后端服务器 [英] Proxy requests to a separate backend server with vue-cli

查看:41
本文介绍了使用 vue-cli 代理请求到单独的后端服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vue-cli webpack-simple 模板来生成我的项目,我想将请求代理到一个单独的后端服务器.如何轻松实现这一目标?

I am using vue-cli webpack-simple template to generate my projects, and I'd like to proxy requests to a separate, backend server. How can this be easily achieved?

推荐答案

如果你使用webpack模板和vue-cli,那么你可以在这个参考文档中找到所需的信息:

If you use webpack template with vue-cli, then you can find the required information in this reference document:

http://vuejs-templates.github.io/webpack/proxy.html

或者现在不用更改模板,您可以将 webpack 模板中的相关配置复制到本地 webpack-simple 模板中.

Or instead of changing your template now, you may copy the relevant config from the webpack template into your local webpack-simple template.

来自我本地设置的更多信息

这是我在 module.exports 下的 config/index.js 中的内容:

This is what I have in my config/index.js under module.exports:

dev: {
    env: require('./dev.env'),
    port: 4200,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true
        },
        '/images': {
            target: 'http://localhost:8080',
            changeOrigin: true
        },
        // and so on...

上面的配置在端口 4200 上运行我的 vue-cli,而我在端口 8080 上运行我的服务器.

The above config runs my vue-cli on port 4200, and I run my server on port 8080.

在评论 #4 和 #5 之后更正了关于 CORS 的信息

注意:

  • dev.proxyTable 中的 changeOrigin 选项(在 webpack 配置中)确保您不需要在服务器 API 响应中提供 CORS 标头.
  • 如果您出于任何原因决定省略 changeOrigin,那么您需要确保您的服务器 API 包含 Access-Control-Allow-Origin: *(或等效的)在其响应标头中.
  • The changeOrigin option in dev.proxyTable (in webpack config) ensures that you do not need to serve CORS headers on your server API responses.
  • If you decide to omit changeOrigin for any reason, then you need to ensure that your server API includes Access-Control-Allow-Origin: * (or equivalent) in its response headers.

参考:

  1. https://stackoverflow.com/a/36662307/654825
  2. https://github.com/chimurai/http-proxy-middleware

这篇关于使用 vue-cli 代理请求到单独的后端服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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