xhr.open如何传输headers
时间: 2024-03-01 14:51:56 浏览: 24
在使用XMLHttpRequest对象的时候,可以通过xhr.setRequestHeader()方法来设置HTTP请求头。该方法需要传入两个参数,第一个参数是HTTP头的名称,第二个参数是HTTP头的值。例如,设置一个名为"Authorization"的HTTP头,它的值为"Bearer token",可以使用以下代码:
```
xhr.setRequestHeader("Authorization", "Bearer token");
```
需要注意的是,这个方法必须在调用xhr.open()方法之后、调用xhr.send()方法之前调用。否则会抛出一个错误。
相关问题
bod为空 我传值方式为 xhr.open(method, url) xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded') Object.keys(headers).forEach(headerkey => xhr.setRequestHeader(headerkey,headers[headerkey])) xhr.send(paramsString)
根据你提供的信息,bod为空的原因可能是你在发送请求时没有将请求体传递给服务器。xhr.send()方法只能发送GET请求,不支持POST请求,因此需要将参数作为请求体传递。可以按照以下方式修改代码:
1.使用POST方法发送请求
```javascript
xhr.open('POST', url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Object.keys(headers).forEach(headerkey => xhr.setRequestHeader(headerkey, headers[headerkey]));
xhr.send(paramsString);
```
2.将参数作为请求体传递
```javascript
xhr.open('POST', url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Object.keys(headers).forEach(headerkey => xhr.setRequestHeader(headerkey, headers[headerkey]));
xhr.send(JSON.stringify({bod: paramsString}));
```
这样,服务器就能正确地解析请求体中的参数了。
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:3000/get'); xhr.send();404
如果你在浏览器中运行此代码,可能会收到 404 错误,因为在发送 XMLHttpRequest 请求时,浏览器会遵循跨域资源共享(CORS)规则,要求服务器在响应中设置特殊的响应头信息。如果服务器没有正确设置这些响应头信息,浏览器会拒绝接受响应,从而导致请求失败。你可以在服务器端设置响应头信息,允许跨域访问,例如:
```
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
```
这样设置之后,服务器就允许跨域访问了。当然,你也可以使用 JSONP 或者其他方法来解决跨域问题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)