0

Cannot load JS file in my app (getting undefined) and I want to emulate the same effect as the tag in the plain HTML.

I have tried

import Api from './api' -> tells me that none of the defined function is a function (don't have any circular dependencies), so my best guess it that Api was not initalized or something?

Tried module.exports on Api -> tells me that Api is undefined

Tried exports.Api -> tells me that the function which i try to call from the Api is not a function

I tried to require and a few more things, which I cannot even recall, and none of it seems to be working. Main issue is that I don't recognize the format of the JS file in question since I never seen a variable declared as a function that contains other functions, so explanation on that might come in handy tbh.


var Api = (function() {
  var requestPayload;
  var responsePayload;
  var messageEndpoint = '/api/message';

  var sessionEndpoint = '/api/session';

  var sessionId = null;

  // Publicly accessible methods defined
  return {
    sendRequest: sendRequest,
    getSessionId: getSessionId,

    // The request/response getters/setters are defined here to prevent internal methods
    // from calling the methods without any of the callbacks that are added elsewhere.
    getRequestPayload: function() {
      return requestPayload;
    },
    setRequestPayload: function(newPayloadStr) {
        requestPayload = JSON.parse(newPayloadStr);
    },
    getResponsePayload: function() {
      return responsePayload;
    },
    setResponsePayload: function(newPayloadStr) {
      responsePayload = JSON.parse(newPayloadStr);
    },
    setErrorPayload: function() {
    }
  };

  function getSessionId(callback) {
    var http = new XMLHttpRequest();
    http.open('GET', sessionEndpoint, true);
    http.setRequestHeader('Content-type', 'application/json');
    http.onreadystatechange = function () {
      if (http.readyState === XMLHttpRequest.DONE) {
        var res = JSON.parse(http.responseText);
        sessionId = res.session_id;
        callback();
      }
    };
    http.send();
  }

  // Send a message request to the server
  function sendRequest(text, context) {
    // Build request payload
    var payloadToWatson = {
      session_id: sessionId
    };

    payloadToWatson.input = {
      message_type: 'text',
      text: text,
    };

    if (context) {
      payloadToWatson.context = context;
    }

    // Built http request
    var http = new XMLHttpRequest();
    http.open('POST', messageEndpoint, true);
    http.setRequestHeader('Content-type', 'application/json');
    http.onreadystatechange = function() {
      if (http.readyState === XMLHttpRequest.DONE && http.status === 200 && http.responseText) {
        Api.setResponsePayload(http.responseText);
      } else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200) {
        Api.setErrorPayload({
          'output': {
            'generic': [
              {
                'response_type': 'text',
                'text': 'Something went wrong.'
              }
            ],
          }
        });
      }
    };

    var params = JSON.stringify(payloadToWatson);
    // Stored in variable (publicly visible through Api.getRequestPayload)
    // to be used throughout the application
    if (Object.getOwnPropertyNames(payloadToWatson).length !== 0) {
      Api.setRequestPayload(params);
    }

    http.send(params);
  }
}());

Code above is provided by IBM (for the Watson Assistant I am trying to work with) and the code is for the Node.JS application which works fine. It works fine since the code above is simply included in the app through the tag in their index.html and voila, it works, but I don't have that ability (read below). My issue is that their app is also a client app and I want to transfer all of that 'back-end' stuff to my REST API and that is why I am trying to use the code above.

3
  • did you try with ` require('./file_name_with_appropriate_path');` ? Commented Jun 13, 2019 at 15:53
  • I did, same TypeError telling me that one of the functions is not a function :( Commented Jun 13, 2019 at 15:57
  • may be, your forgot to export the module like: module.exports = {your js code which will be exported to another .js file} ? Commented Jun 13, 2019 at 16:02

1 Answer 1

1
var Api = (function() {
  var messageEndpoint = "/api/message";

  // Publicly accessible methods defined
  return {
    messageEndpoint: messageEndpoint
  };
})();
module.exports = Api ;

And you can use it like

const api = require("./api");
console.log(api);

So basically just add module.exports = Api ; in api file and you would be able to use it.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that is it, I did try that but overlooked it since I got undefined, and that undefined was coming from a return of the function and not the Api object itself and your function returns a proper data (problem with the service I am using and not the code) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.