CORS - 通过允许服务器上的 Origin 实现没有 JSONP 的跨域 AJAX [英] CORS - Cross-Domain AJAX Without JSONP By Allowing Origin On Server

查看:11
本文介绍了CORS - 通过允许服务器上的 Origin 实现没有 JSONP 的跨域 AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一台服务器上有两个独立的应用程序,其中一个 EmberJS 试图对我的后端 API 进行跨域调用.

I have two separate apps on the same server, with the EmberJS one trying to do cross-domain calls to my backend API.

我设置了后端 API 以允许来自该特定来源的跨域请求.但是,有没有办法避免在这样的设置中使用 JSONP?$.ajax 在发送之前阻止跨域请求.如果不是,CORS 的意义是什么,我实现了哪个服务器端来接受来自我的 JS 前端源的请求?

I set up my backend API to allow cross-domain requests from that specific origin. Is there a way however, to avoid using JSONP with such a set up? $.ajax is blocking cross-domain requests before they ever get sent. If not, what is the point of CORS, which server-side I had implemented to accept requests from my JS front-end source?

编辑

AJAX 请求:

$.ajax({
    url: "api.lvh.me:3000/accounts/login",
    data: cred,
    type: "POST",
    xhrFields: {
        withCredentials: true
    },
    success: function(response){
        alert('succeeded!');
        console.log(response);
        alert(response);
    },
    failure: function(message){
        alert("failed");
        console.log(message);
        alert(message);
    }
});

推荐答案

如果启用 CORS,则无需使用 JSONP.

There is no need to use JSONP if you enable CORS.

Access-Control-Allow-Origin: http://www.example.com

如果在响应中设置了这个标头,那么普通的 XmlHttpRequest 将能够访问响应,就像它像同一个域一样.检查这个标题是否设置正确.

if this header is set in the response, then normal XmlHttpRequest will be able to access the response as if it is like same domain. Check whether this header is set correctly.

如果您使用 jquery,我希望此链接对您有所帮助 CORS POST 请求可以通过普通的 javascript 工作,但为什么不使用 jQuery?

I hope that this link will help you if you are using jquery A CORS POST request works from plain javascript, but why not with jQuery?

更新:例子

var xmlhttp= new XMLHttpRequest();
var url="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control";
xmlhttp.open("GET",url,false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send();

在任何域中尝试此操作,您都会得到响应.

Try this in any domain, you will get response.

更新解决方案:

请求 url 没有http://"导致问题,在前面加上http://"解决了问题

Request url without "http://" caused the problem, prepending "http://" solved the issue

这篇关于CORS - 通过允许服务器上的 Origin 实现没有 JSONP 的跨域 AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆