使用 javascript 设置响应头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17989951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:21:26  来源:igfitidea点击:

Setting response header with javascript

javascriptresponse-headers

提问by Marko ?ilimkovi?

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.

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

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

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

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

我怎样才能使用纯 javascript 做到这一点?没有 jquery 或任何其他库。

This is my current code:

这是我当前的代码:

<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>

回答by T.J. Crowder

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

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

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

我怎样才能使用纯 javascript 做到这一点?没有 jquery 或任何其他库。

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

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

The serverhas 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 browser sends the actual request.

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

  • 浏览器请求访问资源的许可(这称为“预检”请求),告诉服务器它想要访问什么资源等。

  • 服务器用适当的标头回复告诉浏览器是否允许访问。

  • 浏览器发送实际请求。

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

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

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

Details in the Cross-Origin Resource Sharing specification.

跨域资源共享规范详细信息。

回答by mguimard

You cannot do this on client side, your server must send these headers.

您不能在客户端执行此操作,您的服务器必须发送这些标头。