Search code examples
jsonnode.jsrestapiloopback

Trying to send access token from loopback to third party api


I have my API in loopback 3.x. First I created an empty project and right after that I ran npm install loopback-connector-rest --save and lb datasource in the console to have a link to an external API called Userlike. It this URL https://www.userlike.com/api/external/message/chat_meta/.

Then I created a model with no parameters called Messages.

I had no problems executing as I used node . and there was no error, and in localhost:3000 I could visualize my API.

But I had a problem when I clicked GET in the page a 401 error because to access the API in Userlike I needed to send my token so I could get the data, so I modified the datasources.json file and I had this:

{
  "userlikeRESTdatasource": {
    "name": "userlikeRESTdatasource",
    "baseURL": "https://www.userlike.com/api/external/message/chat_meta/",
    "crud": false,
    "connector": "rest",
    "operations": [
      {
        "functions": {
          "getMessages": []
        },
        "template": {
          "method": "GET",
          "url": "https://www.userlike.com/api/external/message/chat_meta/",
          "headers": {
            "accepts": "application/json",
            "content-type": "application/json",
            "authorization": "8c149a3d-4acf-362e-880c-30ec2f5ecaf"
          },
          "responsePath": "$.results.*"
        }
      }
    ]
  }
}

The authorization field I put in the header didn't work as I still received

{
  "error": {
    "statusCode": 401,
    "name": "Error",
    "message": "Authorization Required",
    "stack": "Error: Authorization Required\n 
  }
}

My idea was to do something like:

headers.append('Authorization', '8c149a3d-4acf-362e-880c-30ec2f5ecaf7');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept');

But with loopback. So I could receive the data from the Userlike API and next I could modify or just use the data I wanted.

But I still can't figure out how can I modify my datasources.json or if I need to create something in another file to make it possible to send the token as the authorization to that URL I'm using.


Solution

  • Pass access token with HTTP header by using this

    headers.append('X-Access-Token', '8c149a3d-4acf-362e-880c-30ec2f5ecaf7');
    

    or also pass this token as a parameter.

    ?access_token=8c149a3d-4acf-362e-880c-30ec2f5ecaf7
    

    This will help.