2017-06-08 64 views
1

我正在關注一個博客,用express框架構建我的第一個節點API。但是POST請求沒有返回響應。Express JS節點框架沒有響應post()請求

const app = express(); 

require('./app/routes')(app, {}); 
app.listen(port,() => { 
    console.log('We are live on ' + port); 
}); 

module.exports = function(app, db) { 
    console.log('reached2'); 
    app.post('/notes', (req, res) => { 
    // You'll create your note here. 
    console.log('reached3'); 
    res.send('Hello'); 
    //res.end();; 
    }); 
}; 

這裏是我的控制檯日誌,

reached1 
reached2 
We are live on 8000 

這裏是我的依賴,

"dependencies": { 
    "body-parser": "^1.17.2", 
    "express": "^4.15.3", 
    "mongodb": "^2.2.28" 
    }, 
    "devDependencies": { 
    "nodemon": "^1.11.0" 
    } 

進出口使用的postman客戶端POST。

enter image description here

我試着用匿名函數,但仍然不工作更換脂肪箭頭操作符。

請在這段代碼中指出問題。

+0

要導出調用app.post功能,但你實際上調用該函數的任何地方? –

+0

yes,'require('./app/ routes')(app,{});''''''''''''''我看到函數被調用,因爲控制檯從該函數記錄。 – ProgramCpp

+0

投票結束問題,因爲問題與端口號有關。適用於端口3000. Express/Node/Nodemon確實說它正在監聽端口8000事件。 – ProgramCpp

回答

-1

不用在函數中編寫路由,您可以直接使用它。下面是相同的代碼片段:

const app = express(); 
app.listen(port,() => { 
    console.log('We are live on ' + port); 
}); 

app.post('/notes', (req, res) => { 
    // You'll create your note here. 
    res.send('Hello'); 
}); 
+0

這也不起作用! – ProgramCpp

0

如果你想保持在一個單獨的文件的路徑(這是相當標準的做法),那麼你就需要返回路由器,告訴快遞應用程序使用它。

app.js

const express = require('express'); 
const routes = require('./routes')({}); 

const app = express(); 

app.use('/', routes); 

app.listen(8080,() => { 
    console.log('Listening on 8080'); 
}) 

routes.js

const express = require('express'); 

module.exports = (db) => { 

    const router = express.Router(); 

    router.post('/notes', (req, res) => { 
     res.send('Hello!'); 
    }) 

    // all your other routes here! 

    return router; 

} 

,或者如果你想這樣做,而無需使用express.Router()使用,你可以通過app

app.js

const express = require('express'); 

const app = express(); 

require('./routes')(app, {}); 

app.listen(8080,() => { 
    console.log('Listening on 8080'); 
}) 

routes.js

module.exports = (app, db) => { 

    app.post('/notes', (req, res) => { 
     res.send('Hello!'); 
    }) 

} 
+0

是否有可能沒有路由器?因爲我遵循的博客並不使用它。 – ProgramCpp

+0

@ProgramCpp是的,我已經用第二個例子更新了我的答案。雖然這樣,感覺不太好!你有鏈接到博客? – dan

+0

謝謝丹,會嘗試另一種選擇。這是博客,https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2 – ProgramCpp