我正在嘗試使用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"
}
看起來你正在建立index.js中的所有路由,但是沒有在server.js中引用index.js。您需要在server.js中執行'var myRoutes = require('index.js')'然後'myRoutes(app,db)'來將路由綁定到您的應用。 –