Nimrod Yanai
Nimrod Yanai

Reputation: 819

export function with promise in nodejs

I am trying to import a function from an external file I have, which contains a promise. The resolution of the promise is what should be returned, but I get an error message: The requested module './functions.js' does not provide an export named 'getOkapiToken' The POST request works fine when I run it directly in the server, but I need it in a separate file as it will be used by several different files in the future. This is also the first time I'm using promises, so I'm not sure I handled it properly (though I can't get any errors registered until I deal with the first one).

The functions.js file is built as follows:

import post from 'axios';

export function getOkapiToken(url, user, password) {
    //Get username and password for API
    const auth = {
      "username": user,
      "password": password
    };

    //Create headers for POST request
    const options = {
      method: 'post',
      data: auth,
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': auth.length,
        'X-Okapi-Tenant': 'diku'
      }
    };
      //Make API post call
    post(url+':9130/authn/login', options)
        .then(response => {
          return(response.headers['x-okapi-token'])
        }).catch((err) => {
            return(`There was an error 2: ${err}`)
    })
  }

And I try to import it as follows:

import { getOkapiToken } from './functions3.js'
import settings from './jsons/config.json';
let OkapiKey = await new Promise((resolve,reject) => {
  //Call function to make API post call  
  let keytoken = getOkapiToken(settings.url,settings.userauth,settings.passauth)
  console.log(`There was an error: ${keytoken}`)
  if (keytoken.length == 201) {
    resolve(keytoken)
  } else {
    reject('There was an error')
  }
})

OkapiKey.then((data) => {
  console.log(data)
})
.catch((err) => {
  console.error('I have an error:'+err.code);
})

Upvotes: 1

Views: 1189

Answers (1)

meddy
meddy

Reputation: 395

There are three ways to handle asynchronous task in Javascript and wit Node.JS

  1. Pass in a Callback to run in the asynchronous code
  2. Use a Promise that will either resolve or reject the promise
  3. Use the async keyword in front of the function and place await in front of the asynchronous code.

With that said I was able to get the code to work by running a simple node server and I modified your code just a bit to get a response back from the server.

index.js

const  { getOkapiToken } = require('./functions.js')
const settings = require('./settings.json')
var OkapiKey = getOkapiToken(settings.url,settings.userauth,settings.passauth)
OkapiKey
.then((data) => {
  console.log('I have data'+ data.toString())
})
.catch((err) => {
  console.error('I have an error:'+err.code);
})

functions.js

const post  = require('axios');

const getOkapiToken = (url, user, password) =>
    new Promise(function (resolve, reject) {

      //Get username and password for API
      const auth = {
        "username": user,
        "password": password
      };

      //Create headers for POST request
      const options = {
        method: 'post',
        data: auth,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': auth.length,
          'X-Okapi-Tenant': 'diku'
        }
      };

      post('http://localhost:3000/', options)
          .then(response => {
            resolve(response.data)
            // if (response.headers['x-okapi-token']) {
            //   resolve(response.headers['x-okapi-token']);
            // } else {
            //   reject((error));
            // }
          }).catch((err) => {
            console.error('Response Error:'+err)
      })
    })

exports.getOkapiToken = getOkapiToken;


Upvotes: 2

Related Questions