代码之家  ›  专栏  ›  技术社区  ›  TamerB

Ajax GET请求:后端未接收到x-access-token标头

  •  1
  • TamerB  · 技术社区  · 7 年前

    我试图向一个节点发送一个AJAX GET请求。js微服务。请求应包含在标头中 {'x-access-token': somtoken} 我的请求如下:

    $.ajax({  
       type: "GET",
       url: "http://localhost:3000/api/books",
       headers: {'x-access-token' : sometoken},
       success: function(dataString) { 
           console.log(JSON.stringify(dataString));
       }, error: function(error) {
           console.log(JSON.stringify(error));
       }
    });
    

    然而,在微服务中收到的标题如下:

    { host: 'localhost:3000',
    connection: 'keep-alive',
    'access-control-request-method': 'GET',
    origin: 'null',
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
    'access-control-request-headers': 'x-access-token',
    accept: '*/*',
    'accept-encoding': 'gzip, deflate, sdch, br',
    'accept-language': 'en-US,en;q=0.8' }
    

    因此,它发送了一个错误为403的响应

    当从邮递员发送请求时,服务工作正常。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Alexandru Olaru    7 年前

    你应该试着使用 beforeSend 来自jQuery的钩子

     $.ajax({
      url: "http://localhost:3000/api/books",
      type: "GET",
      beforeSend: function (xhr) {
        xhr.setRequestHeader('x-access-token', token);
      },
      success: function (dataString) {
        console.log(JSON.stringify(dataString));
      }, error: function (error) {
        console.log(JSON.stringify(error));
      }
    });
    
        2
  •  0
  •   TamerB    7 年前

    手动添加代码可以完成后期重新测试,但无法使用x-access-token进行GET

    cores npm package