2017-06-11 39 views
1

我正在嘗試使用node.js創建一個簡單的休息端點。 我下面教程https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2postman返回404爲node.js端點

的文件夾結構值得注意/應用/路由/和文件夾包含index.js路線和note_routes.js文件

我能夠運行命令npm run dev,和輸出顯示爲:

> [email protected] dev /Users/tejanandamuri/Desktop/notable 
> nodemon server.js 

[nodemon] 1.11.0 
[nodemon] to restart at any time, enter `rs` 
[nodemon] watching: *.* 
[nodemon] starting `node server.js` 
We are live on 8000 

此後。在郵遞員,當我嘗試打電話給http://localhost:8000/notes,它與響應主體無法發佈返回404錯誤/注意到

這裏是我的文件:

server.js:

const express  = require('express'); 
const MongoClient = require('mongodb').MongoClient; 
const bodyParser  = require('body-parser'); 
const app   = express(); 
const port = 8000; 
require('./app/routes')(app, {}); 
app.listen(port,() => { 
    console.log('We are live on ' + port); 
}); 

index.js:

// routes/index.js 
const noteRoutes = require('./note_routes'); 
module.exports = function(app, db) { 
    noteRoutes(app, db); 
    // Other route groups could go here, in the future 
}; 

note_routes.js

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

的package.json:

{ 
    "name": "notable", 
    "version": "1.0.0", 
    "description": "my first rest api", 
    "main": "server.js", 
    "dependencies": { 
    "body-parser": "^1.17.2", 
    "express": "^4.15.3", 
    "mongodb": "^2.2.28" 
    }, 
    "devDependencies": { 
    "nodemon": "^1.11.0" 
    }, 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1", 
    "start": "node server.js", 
    "dev": "nodemon server.js" 
    }, 
    "author": "venkata", 
    "license": "ISC" 
} 
+0

看起來你正在建立index.js中的所有路由,但是沒有在server.js中引用index.js。您需要在server.js中執行'var myRoutes = require('index.js')'然後'myRoutes(app,db)'來將路由綁定到您的應用。 –

回答

1

變化server.js線6 require('./routes/note_routes')(app, {});

這是假設你的文件樹看起來是這樣的:

. 
+--/node_modules // this contains a ton of sub-folders 
+--/routes 
+ +--index.js 
+ +--note_routes.js 
+--package.json 
+--server.js 

enter image description here

+0

我改變了require中的路徑後,它顯示如下錯誤:Error:Can not find module'./note_routes' –

+0

嘗試將它改爲require('./ routes/note_routes')(app,{});'didn注意你提到的文件夾結構。 – OneNeptune

+0

@TejaNandamuri你能工作嗎?如果是這樣,請分享您的答案或標記正確的答案。這使得遇到相同或類似問題的其他用戶更容易識別正確的解決方案,而無需閱讀所有討論。 – OneNeptune