weixin_33694172 2015-02-08 07:21 采纳率: 0%
浏览 1129

jQuery AJAX CORs错误

I have a website that takes a GET request and returns a JSON. I can send the website a request using a node server and receive the correct response. However, when I try to send it using client-side javascript:

$.ajax({
    url: '<myurl>',
    type: 'GET',
    crossDomain: true,
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); }
});

I get the error

XMLHttpRequest cannot load <myurl>. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'http://localhost:8080' is
therefore not allowed access.

When I try changing the datatype to jsonp by adding dataType: 'jsonp', to the ajax request, I get the error

Uncaught SyntaxError: Unexpected token :

The chrome developer console tells me the error is coming from the script <myurl>&callback=jQuery21309685717469546944_1423379667604&_=1423379667605, and when I open the script I find the JSON response I am trying to retrieve! but I guess somehow it's being interpreted as a javascript function. Any way to resolve this? I have read many SO answers and tried many approaches to no avail.

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2015-02-08 07:33
    关注

    You will need to change something server-side to make this work from a browser. The server will need to either support JSONP or CORS in order to access it cross domain.

    You cannot make client-only changes to make JSONP or CORS work - the server must cooperate.

    With CORS, the right headers must exist on the http requests between client and server in order to permit the browser to process the cross origin request.

    With JSONP, it is a completely different type of response from the server that makes JSONP work (data wrapped in a javascript script) so the server has to produce this other type of response in order for JSONP to work.


    If you think your server already supports cross origin requests via CORS, then there is probably an error in the implementation somewhere.


    The cross origin restrictions are implemented inside the browser in order to protect users using the browser. Such restrictions are not enforced by a server so servers are not limited to which origins they can connect to.

    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?