gpt4 book ai didi

javascript - 如何使用 Ajax 发送 header

转载 作者:行者123 更新时间:2023-12-03 04:33:53 26 4
gpt4 key购买 nike

我创建了一个静态网站,我想使用此 Ajax 函数将带有 http header 的请求发送到 NodeJs Express REST API。但是当我发送它时,我无法通过 REST API 获取任何 token 字段。

 $.ajax({
beforeSend: function (request) {
request.setRequestHeader("token", 'vjhvjhvjhvjhbjhsbvkjsbvkjsbkvjbskjvb');
},
dataType: "json",
url: "http://localhost:3000/feeds",
success: function (data) {
//do something
}
});

当我用Postman发送它时,我可以很容易地收到它。这是NodeJS中间件

router.use(function (req, res, next) {
res.header("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);

console.log(req.headers.token);
});

我该如何解决这个问题?

最佳答案

AJAX header 可以设置为全局,如下所示。

$.ajaxSetup({
headers: {
'token':'token_vlaue',
'another_field': 'another_field_value'
}
});

关于javascript - 如何使用 Ajax 发送 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com