【问题标题】:How do I call an API endpoint I created from my client-side application?如何调用从客户端应用程序创建的 API 端点?
【发布时间】:2018-12-20 10:35:04
【问题描述】:

我构建了一个服务器端模块,它接受用户的登录名和密码作为参数并返回一个 JSON 对象。我正在尝试使用路由器对象中指定的 API 端点从客户端调用此模块,但我不断收到 404 错误。

不确定如何继续调试问题。

我的服务器模块:

'use strict';

var express = require('express');
var router = express.Router();



// Endpoint to be call from the client side
router.get('/api/endpoint', function(req, res){

    let login = req.params('login')
    let pwd = req.params('pwd')

    //does stuff



  doSomething.then((value) => {
    return res.json(value)
  })
});

module.exports = myModule;

我的客户端模块:

 var MyModule = (function() {
  var endpoint = '/api/endpoint';

  // Publicly accessible methods defined
  return {

    myFunction: myFunction,

  };

    function myFunction(login, pwd) {



    // Built http request
    var http = new XMLHttpRequest();
    http.open('POST', endpoint, true);
    http.setRequestHeader('Content-type', 'application/json');
    http.onreadystatechange = function() {
      if (http.readyState === 4 && http.status === 200 && http.responseText) {
          console.log(http.responseText)
      }
    };

    // Send request
    http.send();

    }

}());

理想情况下,通过单击按钮调用此函数,使用户登录并在相关 JSON 对象旁边返回一个成功/失败布尔值。谢谢!

【问题讨论】:

    标签: node.js http express serverside-javascript


    【解决方案1】:

    看起来您只为端点启用了get 而不是post。尝试将您的 router.get 更改为 router.post

    【讨论】:

    • 谢谢——这有帮助。
    猜你喜欢
    • 2014-04-04
    • 2014-10-04
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多