node.js - 访问 url 参数时出现 Node Js api 404 not found 错误

标签 node.js rest api

我正在制作一个nodejs api,其中我从数据库中获取申请人的所有记录。我的 api 网址是这样的

var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
enter code here
var ApplicantCtrl = require('./controllers/applicantController');
var app = express();
var port = process.env.Port || 8000;
app.use(bodyParser.urlencoded({
 extended: true
}));
 app.use(bodyParser.json());
 app.get('api/applicant/:applicantId/getFullDetails',           
  ApplicantCtrl.getApplicantAllData);
app.listen(port, function() {
console.log('Server is running on port : ' + port);
 });

和applicantController.js代码在这里

var connection = require('./../config');
var helpers = require('../helpers/helper');


module.exports.getApplicantAllData = function(req , res) {
var id = req.params.applicantId;
console.log('in applicantallData');
helpers.getApplicantFullData(id)
    .then((data)=>{
        if(data == null){
            res.send({
                meta : {status : 400, message : 'There is some error with query'}
            });
        }
        else{
            res.send({
                meta : {status : 200, message : 'Success'},
                data : data
            });
        }
    })
    .catch(function(err){
        res.send({
            meta : {status : 500, message : 'Internal Server Error'}
        });
    });

  }

但是api响应是这样的

Cannot GET /api/applicant/23/getFullDetails 404

谁能告诉我这里出了什么问题吗?为什么发现 api 响应是 404?

最佳答案

看起来您在快速应用程序中缺少许多为服务器设置路由的必要代码。我认为这就是“在此处输入代码”部分的用途。

Here is a quick tutorial关于设置一个非常基本的 express 服务器。

对于示例中的 URL,您将需要一个类似于以下内容的路由:

router.get('/api/applicant/:id/getFullDetails', function(req, res) {
  // implementation here
});

此外,不相关但为了更加 RESTFul,您可能需要将 URL 稍微更改为:/api/applicants/:id/fullDetails

关于node.js - 访问 url 参数时出现 Node Js api 404 not found 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612904/

相关文章:

javascript - Windows Live API 连接问题

ruby-on-rails - 使用 HTTParty 的非常基本的 Rails 4.1 API 调用

javascript - Node js中的Promise中间件回调函数如何使用多个呢?

forms - 在基于 POST 的 HTML 表单中, "action"应该指向什么 URL

angular - 使用YouTube API和Angle搜索电影预告片

rest - SharePoint Online : REST API for List, 调用筛选器并限制返回项

api - Rest API 调用,使用 RestSharp 调用 ASP.NET Web API

javascript - 如何使抛出的错误在 Promise 之外可见?

javascript - NodeJS 将响应输出返回到对象数组

node.js - 这是在 NodeJS 中控制异步的好方法吗?