使用javascript设置响应头 [英] Setting response header with javascript

查看:1636
本文介绍了使用javascript设置响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中从URL收集json值时遇到了麻烦。当我尝试获取它们时,控制台中会显示错误日志,说access-control-allow-origin不允许来源。

I'm having troubles with collecting json values from a URL in my application. When I try to get them a error log is displayed in the console saying that origin is not allowed by access-control-allow-origin.

我研究了一下,发现了必须将响应标头设置为Access-Control-Allow-Origin:*

I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *

如何使用纯JavaScript进行操作?没有jquery或任何其他库。

How can I do that using pure javascript? No jquery or any other library.

这是我目前的代码:

<script type="text/javascript">
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://example.com/id=69", false );
    xmlHttp.send( null );
    console.log("JSON values from URL: ");
    console.log(xmlHttp.responseText);
</script>


推荐答案


我研究了一下并发现必须将响应标头设置为Access-Control-Allow-Origin:*

I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *

如何使用纯JavaScript进行操作?没有jquery或任何其他库。

How can I do that using pure javascript? No jquery or any other library.

你不能,除非你的服务器正在运行JavaScript( NodeJS等。

You can't, not unless your server is running JavaScript (NodeJS, etc.).

服务器必须允许从文档的来源访问资源。它的工作方式是:

The server has to allow access to the resource from the origin of your document. The way it works is:


  • 浏览器要求访问资源的权限(这称为预检请求),告诉服务器它想要访问哪些资源等。

  • The browser asks permission to access the resource (this is called a "preflight" request), telling the server what resource it wants access to, etc.

服务器回复相应的标题,告诉浏览器是否允许访问。

The server replies with the appropriate headers telling the browser whether access will be allowed.

浏览器发送实际请求。

服务器响应它(再次包括相关标题)。

The server responds to it (again including the relevant headers).

我认为有些情况下不需要飞行前。所有这些都是由 XMLHttpRequest 对象为您处理的。

I believe there are situations where the pre-flight isn't necessary. All of that is handled for you by the XMLHttpRequest object.

跨源资源共享规范

这篇关于使用javascript设置响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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