如何在不获取%22引号的情况下将CURL请求转换为AJAX调用?

时间:2018-08-08 17:02:11

标签: javascript node.js ajax curl

我有一个正常运行的CURL请求:

curl --request GET \
 --url http://localhost:3001/api/v1/protected/getmydetails \
 --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2dvbnRvLmNvbSIsImF1ZCI6Im5vZGVqcy1qd3QtYXV0aCIsImV4cCI6MTUzMzc2OTE0MCwic2NvcGUiOiJmdWxsX2FjY2VzcyIsInN1YiI6ImxhbGFsYW5kfGdvbnRvIiwianRpIjoiQktBZW9KUVNBY3dBZ1A0dyIsImFsZyI6IkhTMjU2IiwiaWF0IjoxNTMzNzQ0MzQwfQ.xM6n2NNEoyY234vbNEnHJsp3My9BmnYtzd1JHmvIyUU' \
  --header 'Content-Type: application/json' \
 --data '{
  "id_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIwIjoidCIsIjEiOiJvIiwiMiI6Im0iLCIzIjoibSIsIjQiOiJ5IiwiNSI6Il8iLCI2IjoiTCIsIjciOiJhIiwiOCI6InciLCJpYXQiOjE1MzM3NDQzNDAsImV4cCI6MTUzNTU0NDM0MH0.WZ47z_xytiyH3LlEYsfvApIfa4H92Tf2sGsGFZ4rRyE"
}'

但是,我很难形成相应的AJAX调用。

<script>
var id_tok = Cookies.get('id_token');
var access_tok = Cookies.get('access_token');

var dataLoad = JSON.stringify({
  id_token: id_tok
});

$.ajax({
 type: 'GET',
  url:   'http://localhost:3001/api/v1/protected/getmydetails',
 headers: { Authorization: 'Bearer ' + access_tok },
  data: dataLoad,
  contentType: 'application/json'
}).done(function(data) {
  console.log(data);
  console.log('data called success');
});

我检查了具有请求URL的Chrome中的网络通话:

http://localhost:3001/api/v1/protected/getmydetails?{%22id_token%22:%22eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIwIjoidCIsIjEiOiJvIiwiMiI6Im0iLCIzIjoibSIsIjQiOiJ5IiwiNSI6Il8iLCI2IjoiTCIsIjciOiJhIiwiOCI6InciLCJpYXQiOjE1MzM3NDQ4ODgsImV4cCI6MTUzNTU0NDg4OH0.ixgm2LHb6iPAbrfQmtwINin_RBeBa5nu29yevbtEi74%22}
Request Method: GET

我非常确定将错误范围缩小到id_token的传输范围内,并将“”解析为%22

我不明白为什么引号被翻译成%22而不是引号?

node.js服务器返回500 (Internal Server Error) which is caused by a QueryResultError: 0

1 个答案:

答案 0 :(得分:1)

正如@ kevin628在评论中所说,%22是在http请求中发送"的正确方法。我几乎可以确定您的问题在$.ajax的标题中,而不是headers: { Authorization: 'Bearer ' + access_tok },您应该尝试

beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", 'Bearer ' + access_tok);
  },

然后,代码应类似于:

$.ajax({
  type: 'GET',
   url:   'http://localhost:3001/api/v1/protected/getmydetails',
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", 'Bearer ' + access_tok);
  },
   data: dataLoad,
   contentType: 'application/json'
 }).done(function(data) {
   console.log(data);
   console.log('data called success');
 });