javascript - 如何在AJAX中形成授权CURL请求?

标签 javascript ajax curl express-jwt

我有以下 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/

相关文章:

javascript - 使用 React 获取数组中的下一个/上一个项目

javascript - 单击时从一个元素到多个元素绘制一条线

javascript - 在单独的数组中显示两个数组的相同元素

curl - 如何设置 cURL 默认 --insecure 选项?

javascript - 在特定上下文中执行通过 .ajax 加载的 &lt;scripts>

ajax - "User is typing"聊天功能

jquery - Bootstrap 选项卡无法通过 AJAX 在模式中工作

javascript - Controller 没有接收到数据?

php - 是否可以在 PHP 中使用带有相对路径的curl?

upload - 如何使用 CURL 将文件上传到受密码保护的 HTTPS 站点?