Javascript 在页面重定向上设置自定义请求标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35236874/
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
Setting custom request header on a page redirect
提问by cmac
I have a web application lets call it server1:8080/amcd this application has a setting in it that allows a user to be auto logged in when i pass in a custom request header in the page request. This custom header is called "REMOTE_USER".
我有一个 Web 应用程序,可以将其称为 server1:8080/amcd,该应用程序中有一个设置,允许用户在我在页面请求中传入自定义请求标头时自动登录。此自定义标头称为“REMOTE_USER”。
My plan is to have another page on another web application, lets call it server2:8080/ssoRedirect/test.html this app on server 2 is acting like a filter where i will pass in a URL parameter such as server2:8080/ssoRedirect/test.html?UserName=user1 this page will take the "user1" parameter and redirect to server1:8080/amcd page while injecting the "user1" value in the "REMOTE_USER" page request.
我的计划是在另一个 web 应用程序上有另一个页面,我们称之为 server2:8080/ssoRedirect/test.html 服务器 2 上的这个应用程序就像一个过滤器,我将传入一个 URL 参数,例如 server2:8080/ssoRedirect/ test.html?UserName=user1 此页面将采用“user1”参数并重定向到 server1:8080/amcd 页面,同时在“REMOTE_USER”页面请求中注入“user1”值。
Any advice in how to I might accomplish this?
关于如何实现这一点的任何建议?
I was looking at some simple javascript like below but could not get it to work.
我正在查看一些像下面这样的简单 javascript,但无法让它工作。
<script>
var url = "http://localhost:8080/index.html?userName=user1"; // or window.location.href for current url
var usernameParam = /userName=([^&]+)/.exec(url)[1];
var result = usernameParam ? usernameParam : 'myDefaultValue';
function customHeader(remoteinput, userinput) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader(remoteinput, userinput);
}
window.location.href = "http://ephesoft.eastus2.cloudapp.azure.com:8080/dcma/";
</script>
I am able to make this work when I use the Modify header plugin for chrome and firefox.
当我使用 chrome 和 firefox 的 Modify header 插件时,我能够完成这项工作。
回答by kamikazeOvrld
A web page can not set HTTP request headers unless you are making an async request using XMLHttpRequest. In this case you are not, you are doing a redirect, like clicking on an href. Instead of relying on custom headers, depending on your backend use any one of these:
除非您使用 XMLHttpRequest 发出异步请求,否则网页无法设置 HTTP 请求标头。在这种情况下,您不是,您正在执行重定向,例如单击 href。不依赖于自定义标头,根据您的后端使用以下任何一种:
- Cookies
- GET variables
- POST variables
- 饼干
- 获取变量
- POST 变量