5

I have a simple API route set up in Express (consumed mainly via my Angular frontend):

 app.post('/api/sendEmail', emailApi.sendEmail);

I've made a module that sits in my backend and also needs to call this service. I figured the easiest way was to do a POST request:

  request({
    url: '/api/sendEmail',
    method: 'POST',
    json: {
      template: template.toLowerCase(),
      obj: mailObj
    }
  }, function(error, response, body){
    console.log('error', error);
    console.log('response', response);
    console.log('body', body);
  });

However, I get this error:

 Error: Invalid URI "/api/sendEmail"

What am I doing wrong here?

JVG
  • 20,198
  • 47
  • 132
  • 210
  • hostname is required in the url. And, btw, your module that tries to call the /api/sendEmail resides in different `node.js` application ? – Mukesh Sharma Jan 06 '17 at 06:15
  • Does this answer your question? [Calling Express Route internally from inside NodeJS](https://stackoverflow.com/questions/38946943/calling-express-route-internally-from-inside-nodejs) – abernier Dec 29 '19 at 11:57

4 Answers4

5

Change Url to'http://127.0.0.1:3000/api/sendEmail', because you're calling an internal api with in express or you can also use localhost in place of 127.0.0.1.

request({
    url: 'http://127.0.0.1:3000/api/sendEmail', //on 3000 put your port no.
    method: 'POST',
    json: {
        template: template.toLowerCase(),
        obj: mailObj
    }
}, function (error, response, body) {
    console.log({error: error, response: response, body: body});
});
Shekhar Tyagi
  • 1,644
  • 13
  • 18
4

emailApi.sendEmail is just a function. You are much better off calling it directly. Using the network in this manner would be a serious waste of resources.

On a practical note, there are some complex issues about how to address yourself on the network. Usually you can accomplish this via localhost, but there's no guarantee that the server is listening at that address. So you'll have to take that into account.

Seth Holladay
  • 8,951
  • 3
  • 34
  • 43
2

You need to use an absolute URI (including the protocol, domain, and port if it's not listening on the default port).

For example, if you know that the server will be listening at localhost:3000, you would want to replace your url value with 'http://localhost:3000/api/sendEmail'.

jmar777
  • 38,796
  • 11
  • 66
  • 64
1

Assuming you are not using a web server like nginx and are developing on localhost. The express app does not know from where the request has originated. Try setting your Url as http://localhost:300/api/sendEmail.

Nitish Phanse
  • 552
  • 1
  • 9
  • 16