我有以下 CURL 请求,需要 JWT token 才能访问express.js 中的 protected 路由。这个请求工作正常。
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}
关于javascript - 如何在AJAX中形成授权CURL请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51749670/