您好,欢迎访问一九零五行业门户网

api服务器与前端服务器之间如何解决跨域问题?

浏览器请求前端服务器的静态资源,html、css之类的,
然后浏览器再进行ajax请求api服务器,产生了跨域问题。
我目前想的方案,
一是把前后端资源都置于同一域名下,但是感觉不是太合理。
二是使用反向代理,但是没弄过不清楚是不是合适。
请问如何通过后端解决此问题呢?
回复内容: 浏览器请求前端服务器的静态资源,html、css之类的,
然后浏览器再进行ajax请求api服务器,产生了跨域问题。
我目前想的方案,
一是把前后端资源都置于同一域名下,但是感觉不是太合理。
二是使用反向代理,但是没弄过不清楚是不是合适。
请问如何通过后端解决此问题呢?
跨域基本上有以下几种解决方案
jsonp
cors
window.name
document.domain
5.location.hash
6.window.postmessage()
具体可参考以下文章https://github.com/rccoder/bl...
api服务器设置跨域头即可,如果你是spring写的,可以用类似如下的代码
@componentpublic class corsfilter implements filter { @override public void destroy() { } @override public void dofilter(servletrequest req, servletresponse res, filterchain chain) throws ioexception, servletexception { httpservletresponse response = (httpservletresponse) res; httpservletrequest request = (httpservletrequest) req; response.setheader(access-control-allow-origin, 你的前端服务器地址); response.setheader(access-control-allow-methods, post, put, get, options, delete, head, patch); response.setheader(access-control-max-age, 3600); response.setheader(access-control-allow-headers, x-requested-with, x-auth-token, content-type); response.setheader(access-control-expose-headers, x-requested-with, x-auth-token, content-type, x-total-count); response.setheader(access-control-allow-credentials, true); if (!options.equalsignorecase(request.getmethod())) { chain.dofilter(req, res); } } @override public void init(filterconfig config) throws servletexception { }}
举例,有两个项目:p 以及 api
那么调用方式类似:p前端 -》p后端 -》api
题主后端nodejs的,可以采用一下代码实现跨域,如果是express,建议包装成middleware
res.setheader('access-control-allow-origin', req.headers.origin);res.setheader('access-control-allow-credentials', true);res.setheader('access-control-allow-methods', 'post, get, put, delete, options');res.setheader('access-control-allow-headers','x-requested-with,content-type');
最佳答案已经有了,别忘了请求的时候 withcredentials: true 以带上 cookie
jsonp 可以参考下
access-control-allow-origin:前端域名
个人觉得还是利用反向代理最靠谱
可能使用nginx进行反向代理比较方便,设置跨域响应头并不能全部兼容ie
反向代理比较简单
node 写的后台代码采用express/koa的话直接在后端代码里引入cors()中间件即可
用nginx做反向代理比较方便呢
随便在api服务器上放个js文件,前端引用一下,之后是不是就没有跨域问题了,就像调用外部统计那种逻辑。
其它类似信息

推荐信息