为什么我的JavaScript代码得到“所请求的资源上没有'Access-Control-Allow-Origin'标头"?邮递员没有时出现错误? [英] Why does my JavaScript code get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?

查看:207
本文介绍了为什么我的JavaScript代码得到“所请求的资源上没有'Access-Control-Allow-Origin'标头"?邮递员没有时出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过连接到 JavaScript 进行授权://en.wikipedia.org/wiki/Representationalalstate_transfer#RESTful_web_services"rel =" noreferrer> RESTful 烧瓶中内置的> API .但是,当我发出请求时,出现以下错误:

I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:

XMLHttpRequest无法加载 http://myApiUrl/login .所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问原始空".

XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我知道API或远程资源必须设置标头,但是当我通过Chrome扩展程序发出请求时为什么起作用?

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

这是请求代码:

$.ajax({
    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    }
})
    .done(function( data ) {
        console.log("done");
    })
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
    });

推荐答案

如果可以处理 JSON 作为回报,然后尝试使用 JSONP (请注意 P 最后)以在域之间进行发言:

If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:

$.ajax({
  type: "POST",
  dataType: 'jsonp',
  ...... etc ......

此处了解更多有关

JSONP的出现-本质上是一种共识性的跨站点脚本黑客-开启了强大的内容混搭之门.许多著名的网站都提供JSONP服务,使您可以通过预定义的API访问其内容.

The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.

这篇关于为什么我的JavaScript代码得到“所请求的资源上没有'Access-Control-Allow-Origin'标头"?邮递员没有时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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