简体   繁体   English

使用 Express 未调用 NodeJS 路由

[英]NodeJS routes not getting called using Express

I am trying to build a basic rest api using nodeJS.我正在尝试使用 nodeJS 构建一个基本的 rest api。 But when I'm trying to call any endpoint none of them are getting called.但是当我尝试调用任何端点时,它们都没有被调用。 What changes should i make in order to make it work.我应该进行哪些更改才能使其正常工作。 Please help.请帮忙。

const express = require('express') ;
const app = express() ;
const morgan = require('morgan') ;
const bodyParser = require('body-parser') ;

const productRoutes = require('./api/routes/products') ;
const orderRoutes = require('./api/routes/orders') ;

console.log('abc1') ;

//middleware
app.use(morgan('dev')) ;
app.use(express.urlencoded({ extended: true }));
app.use(express.json);

console.log('abc2') ;

//routes
app.use('/products' , productRoutes ) ;
//console.log('abc5') ;
app.use('/orders' , orderRoutes) ;


//delete it later
app.get('/' , (req , res, next) => {
    res.status(200).json({
        message: 'done'
    }) ;
}) ;
//delete end

//for 404 / not found error
app.use((req,res,next) => {
    const error = new Error('not found');
    error.status = 404 ;
    next(error);
});

//handle any error
app.use((error , req, res,next) => {
    res.status(error.status || 500) ;
    res.json({
        message : error.message 
    }) ;
});

module.exports = app ;

my app.js file我的 app.js 文件

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

router.get('/' , (req,res,next) =>{
    console.log('abc') ;
    res.status(200).json({
        message : 'In get routes'
    }
    ) ;
}) ;

router.post('/' , (req,res,next) =>{
    res.status(201).json({
        message : 'In post routes'
    }
    ) ;
}) ;

router.get('/:productId' , (req,res,next) =>{
    res.status(200).json({
        message : 'In get routes' + req.params.productId 
    }
    ) ;
}) ;

module.exports = router ;

my products.js file我的 products.js 文件

const http = require('http') ;
const app = require('./app') ;

const port = process.env.PORT || 3000 ;
console.log(port) ;

const server = http.createServer(app);

server.listen(port) ;

my server.js file我的 server.js 文件

When I'm trying to run the server it runs normally.当我尝试运行服务器时,它运行正常。 And the console.logs are also working fine.并且 console.logs 也工作正常。 And also no error is getting thrown.而且也没有错误被抛出。

First, change your:首先,更改您的:

app.use(bodyParser.json);

to:到:

app.use(bodyParser.json())

Second, you are not listening to any port.其次,您没有监听任何端口。 You need to add this to your app.js:您需要将其添加到您的 app.js 中:

const port = 4000
app.listen(port, () => console.log(`App is at port: ${port}!`))

and yes, add a slash to the route(s):是的,在路由中添加一个斜杠:

app.use('/products', productRoutes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM