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

 martinsleibert_471 发布于 2022-11-27 09:48

问题:

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

postman 截图:

Vue 的代码如下:

结果报错是这样的:

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或者代码的话,感激不尽。

2 个回答
  • 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

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

    2022-11-27 10:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有