dongwei8729 2019-07-09 11:07
浏览 92

jQuery AJAX http GET跨域 - 响应中需要的标头

I've made a web application running on domain http://app.mydomain.tld and I've APIs on https://api.mydomain.tld (APIs are not developed by me).

I'm doing an AJAX HTTPs GET call with jQuery using this method:

$.ajax({
    url: "https://api.mydomain.tld/GetSomething/read.php",
    method: "GET",
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    async:false,
    headers: {"Accept": "application/json; odata=verbose" },
    success: function (data) { doSomething(); },
    error: function (data) { showError(); }
});

This call is returning an error like NetworkError: failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://api.mydomain.tld/GetSomething/read.php'.

I've added the Access-Control-Allow-Origin extension for Chrome and the call is working fine.

So I've checked response headers. When Chrome extension is NOT enabled I've this response headers:

Access-Control-Allow-Origin: *

When the extension is enabled I've these headers:

Access-Control-Allow-Headers: access-control-allow-methods,access-control-allow-origin
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *

So my question, that could have an obvious answer, is: are these headers required to make correct cross domain calls? If yes, do my APIs need the below additional code?

<?php
header("Access-Control-Allow-Origin","*");
header("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, HEAD, OPTIONS");
header("Access-Control-Allow-Headers","access-control-allow-methods,access-control-allow-origin");
?>

Is correct what I said or am I missing something to make my call working without changing APIs code?

PS: if possibile I would not use JSONP.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 有没有帮写代码做实验仿真的
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥30 vmware exsi重置后登不上
    • ¥15 c++头文件不能识别CDialog
    • ¥15 Excel发现不可读取的内容
    • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
    • ¥20 yolov5自定义Prune报错,如何解决?
    • ¥15 电磁场的matlab仿真