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

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 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)