【问题标题】:Vuejs proxy not working with webpack templateVuejs 代理不适用于 webpack 模板
【发布时间】:2017-09-11 16:04:13
【问题描述】:

我正在使用本地主机上的 webpack 模板开发一个 vuejs 项目,即 url:localhost:8080,但我有一个在 https://foo.bar.com 中运行的快速服务器

过去,我一直通过禁用 CORS 向 express 服务器发出直接请求,但现在我尝试通过代理发出请求。

根据这个API Proxying During Development,我已将以下内容添加到我的config/index.js

proxyTable: {
  // proxy all requests starting with /api to jsonplaceholder
  '/': {
  target: 'https://foo.bar.com',
  changeOrigin: true,
  pathRewrite: {
  '^/': ''
  }
}

在我的登录页面components/login.vue

我有这样的事情:

...
methods: {
  Login(){
     // trying 3 times with different urls
    api.request('post', 'login', {email, password}).then().catch()
    api.request('post', '/login', {email, password}).then().catch()
    api.request('post', 'https://foo.bar.com/login', {email, password}).then().catch()
  }   
}

但我收到这样的错误:

Failed to load https://foo.bar.com/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

【问题讨论】:

  • CORS 未被禁用.. 交叉验证您的代码
  • 显然它没有被禁用。问题是怎么做。

标签: webpack proxy vue.js cors vuejs2


【解决方案1】:

您需要在您的 express 应用程序中启用 CORS,如下所示

从 npm 安装 CORS 包

$ npm install cors

在您的快速应用程序中启用如下代码

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/api/message', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

如需根据需要定制 cors 包的更多信息,请参考https://github.com/expressjs/cors

【讨论】: