我在Node.js的新手,但我更努力一點設置在節點+的結構表達js.I先從前端和單獨的API做structure.I爲API和前端放置一個app.js,但我的API不工作。它給錯誤不能得到/ API /用戶,當我打電話http://localhost:3000/api/users。請幫助節點+快遞JS API不工作
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(控制器)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
這裏是如何建立在明確的的NodeJS例如,您可能會發現有用:https://expressjs.com/en/starter/hello-world.html – Giovanni