简体   繁体   English

从 http 网页请求本地资源时响应是 401 错误

[英]Response is a 401 error when requesting local resource from http webpage

Chrome is throwing Chrome 正在抛出

XMLHttpRequest cannot load http://127.0.0.1:8006/test No 'Access-Control-Allow-Origin' header is present on the requested resource. XMLHttpRequest 无法加载http://127.0.0.1:8006/test请求的资源上不存在'Access-Control-Allow-Origin'标头。 Origin ' http://xxx.yyy.com ' is therefore not allowed access.因此不允许访问来源' http://xxx.yyy.com '。 The response had an HTTP status code 401.响应的 HTTP 状态代码为 401。

I am opening a popup with HTTP and making a request to a local HTTP server created by Java.我正在使用 HTTP 打开一个弹出窗口,并向由 Java 创建的本地 HTTP 服务器发出请求。

It's working fine in all machines except in some different machine, the browser throws the above mentioned error.除了在某些不同的机器上,它在所有机器上都工作正常,浏览器抛出上述错误。

As per my understanding, getting this error in HTTP to HTTP is a bit strange.据我了解,在HTTPHTTP中出现此错误有点奇怪。

It's not strange at all – 127.0.0.1:8006 and xxx.yyy.com are different origins, and the Java server is not sending the Access-Control-Allow-Origin header that would tell the broswer it's okay.这一点都不奇怪127.0.0.1:8006 :8006 和xxx.yyy.com是不同的来源,Java 服务器没有发送Access-Control-Allow-Origin标头来告诉浏览器它没问题。

More details at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS更多详细信息,请访问https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Basically, the Java server needs to add the Access-Control-Allow-Origin header with either an allowed CORS origin or a wildcard (which would allow any origin):基本上,Java 服务器需要添加带有允许的 CORS 来源或通配符(这将允许任何来源)的Access-Control-Allow-Origin标头:

  • Access-Control-Allow-Origin: *
  • Access-Control-Allow-Origin: http://xxx.yyy.com (including the protocol, since http and https are different origins in the browser's eyes) Access-Control-Allow-Origin: http://xxx.yyy.com (包括协议,因为http和https在浏览器眼中是不同的来源)

You have to add headers in server side where you are calling that URL for web service implementation.您必须在调用该 URL 的服务器端添加标头以实现 Web 服务。 This will help you to understand, how the headers are added in java.将帮助您理解如何在 java 中添加标头。

For eg:例如:

.header("Access-Control-Allow-Origin", "*")

If still you want to avoid the cross origin error.如果您仍然想避免cross origin错误。 In this case, I suggest you to use this extension with chrome: Chrome extension for cors .在这种情况下,我建议您将此扩展程序与 chrome 一起使用: Chrome extension for cors

This will help you to avoid cross origin error in browser only in your machine for the development purpose.这将帮助您避免仅在您的机器上用于开发目的的浏览器中的跨源错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM