vue开发中,向服务器请求数据发生跨域,无法得到服务器json数据问题

问题:

在开发一个vue小项目,后台用nodejs搭的,向服务器发送正确的用户名密码会得到一个token,用postman可以正确获得。但是在vue里怎么实现?

postman 截图:

clipboard.png

Vue 的代码如下:

vuecode

结果报错是这样的:

error

XMLHttpRequest cannot load http://localhost:8000/api/aut... 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.

Uncaught (in promise) Response {url: "http://localhost:8000/api/authenticate", ok: false, status: 0, statusText: "", headers: Headers…}

请问怎么才能做到传一个jsond对象给服务器,然后获取服务器返回的json对象,然后在页面能够获取(渲染)?

如果能提供demo或者代码的话,感激不尽。

阅读 7.7k
3 个回答
app.all('*', (req, res, next) => {
  var origin = req.headers.origin;
  res.header('Access-Control-Allow-Origin', origin);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, token');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');
  next()
});

最简单来说,是这样的,在express下。当然你应该对origin进行下限制,设置一个 白名单。
ruanyif

MDN

新手上路,请多包涵

如果仅在开发时端口不同,上线是从同一个服务中取数据,可设置webpack-dev-server的proxy来解决。
但是如果要取的数据确实是跨域服务的。并且项目对兼容性要求不高,那可以使用cors技术。通过设置http请求头即可。不过这个需要前后端都进行修改。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题