Vuejs代理不使用webpack模板

时间:2017-09-11 16:04:13

标签: webpack proxy vue.js cors vuejs2

我正在使用localhost上的webpack模板开发一个vuejs项目,即url:localhost:8080,但我在https://foo.bar.com

中运行了一个快速服务器

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

根据此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.

1 个答案:

答案 0 :(得分:0)

您需要在快速申请中启用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