在开发一个vue小项目,后台用nodejs搭的,向服务器发送正确的用户名密码会得到一个token,用postman可以正确获得。但是在vue里怎么实现?
结果报错是这样的:
请问怎么才能做到传一个jsond对象给服务器,然后获取服务器返回的json对象,然后在页面能够获取(渲染)?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…}
如果能提供demo或者代码的话,感激不尽。
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请求头即可。不过这个需要前后端都进行修改。