从 Express 中调用内部 API

JVG*_*JVG 5 javascript node.js express

我在 Express 中设置了一个简单的 API 路由(主要通过我的 Angular 前端使用):

 app.post('/api/sendEmail', emailApi.sendEmail);
Run Code Online (Sandbox Code Playgroud)

我已经制作了一个位于后端的模块,并且还需要调用此服务。我认为最简单的方法是执行 POST 请求:

  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);
  });
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

 Error: Invalid URI "/api/sendEmail"
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

小智 5

将 Url 更改为“ http://127.0.0.1:3000/api/sendEmail ”,因为您正在使用 Express 调用内部 api,或者您也可以使用 localhost 代替 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});
});
Run Code Online (Sandbox Code Playgroud)


jma*_*777 2

您需要使用绝对 URI(如果未侦听默认端口,则包括协议、域和端口)。

例如,如果您知道服务器将在 处侦听localhost:3000,您可能需要将您的url值替换为'http://localhost:3000/api/sendEmail'