javascript - vue开发中,向服务器请求数据发生跨域,无法得到服务器json数据问题
PHPz
PHPz 2017-04-11 11:28:52
[JavaScript讨论组]

问题:

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

PHPz
PHPz

学习是最好的投资!

全部回复(1)
PHP中文网
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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号