如何在 AJAX 中形成授权 CURL 请求?
How to form a authorization CURL request in AJAX?
我有以下 CURL 请求需要 JWT 令牌才能访问 express.js 中的受保护路由。此请求工作正常。
curl --request GET \
--url http://localhost:3001/api/v1/protected/random-quote \
--header 'Authorization: Bearer eyJ0xxxxQ.NLNOn1caBeGFlPRnsSjLDIKFggMItcm-dl5PKOjlLxs' \
--header 'Content-Type: application/json'
如何制定相应的AJAX请求?
<script>
var id_tok = Cookies.get('id_token');
var access_tok = Cookies.get('access_token');
var headersOb = 'Authorization: Bearer ' + access_tok;
$.ajax({
type: 'GET',
url: 'http://localhost:3001/api/v1/protected/random-quote',
headers: headersOb,
contentType: 'application/json',
dataType: 'json'
}).done(function(data) {
console.log(data);
console.log('data called success');
});
</script>
使用上面的 AJAX 请求我得到以下错误:
VM9599 jquery.min.js:3049 GET http://localhost:3001/api/v1/protected/random-quote 401 (Unauthorized)
需要将对象传递给 headers
选项
headers: {'Authorization': 'Bearer ' + access_tok}
我有以下 CURL 请求需要 JWT 令牌才能访问 express.js 中的受保护路由。此请求工作正常。
curl --request GET \
--url http://localhost:3001/api/v1/protected/random-quote \
--header 'Authorization: Bearer eyJ0xxxxQ.NLNOn1caBeGFlPRnsSjLDIKFggMItcm-dl5PKOjlLxs' \
--header 'Content-Type: application/json'
如何制定相应的AJAX请求?
<script>
var id_tok = Cookies.get('id_token');
var access_tok = Cookies.get('access_token');
var headersOb = 'Authorization: Bearer ' + access_tok;
$.ajax({
type: 'GET',
url: 'http://localhost:3001/api/v1/protected/random-quote',
headers: headersOb,
contentType: 'application/json',
dataType: 'json'
}).done(function(data) {
console.log(data);
console.log('data called success');
});
</script>
使用上面的 AJAX 请求我得到以下错误:
VM9599 jquery.min.js:3049 GET http://localhost:3001/api/v1/protected/random-quote 401 (Unauthorized)
需要将对象传递给 headers
选项
headers: {'Authorization': 'Bearer ' + access_tok}