如何在帮助获取中在标头中传达身份验证令牌?

时间:2018-08-22 19:27:24

标签: javascript node.js

我需要在请求时将用户数据发送到我的端点(rest api),但是仅当从js端发出请求时才会出现401错误。如果邮递员提出要求,我将获得200状态。我按照文档中的说明进行了所有操作。供参考:从Node.js发出请求。谢谢

var token = 'Token 897d3c9991952bc715fcf6c3e262e5b3866342';
var myHeaders = new Headers();
myHeaders.append('Authorization', token);
fetch(this.domain + '/v1.0/user/data/', {method: 'GET', headers: myHeaders, mode: 'no-cors'})
.then(response => {
        if (response.ok) {
            return response.json();
        } else {
                throw new Error('error');
        }
  })

1 个答案:

答案 0 :(得分:0)

选中此链接https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch,也可以使用axios发出请求。

const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://<host>:<port>/<end-point>?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

获取:

// Example POST method implementation:

postData(`http://<host>:<port>/<end-point>`, {answer: 42})
  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
  .catch(error => console.error(error));

function postData(url = ``, data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
}