简体   繁体   中英

Output JSON object in node js using express

This is my first time using Node and I am using the express framework. I am trying to output a json object when on the "calendar" page (seen in main.js). When I run the router (main.js) I get this error: Error: ENOENT, no such file or directory '/Users/Macbook/Desktop/node/views/('calendar.ejs')'

Basically I want to output my JSON object defined in main.js into my html file. Can someone please explain to me why the server cannot find the calendar file. It can find index.ejs but not calendar. And is this the right way to do what I want to achieve?

Below is the directory structure I have setup:

-------node_modules
-------routes
-------------main.js
-------views
------------calendar.ejs
------------index.ejs
-------package.json
-------server.js

This is my server.js code:

var express=require('express');
var app=express();

require('./routes/main')(app);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

var server=app.listen(3000,function(){
    console.log("We have started our server on port 3000");
});

This is my main.js code:

module.exports=function(app){

    app.get('/', function(req,res){
        res.render('index',{title:"Home page"});
    });

    app.get('/calendar',function(req,res){
        res.json({"foo": "bar"});
    });
}

Just a guess.

First you set the GET /calendar route with require('./routes/main')(app); .

Then you overwrite the GET /calendar route with app.set('views',__dirname + '/views'); .

You need to choose whether the GET /calendar returns rendered HTML or the JSON data.

Few things to note :

Since your view files are of .ejs extensions so you can comment below line.( documentation )

app.engine('html', require('ejs').renderFile);

It is convention to pass the `app' reference to routers after you have set all the configurations, middleware order matters when working on ExpressJS.

server.js

var express=require('express');
var app=express();
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');
require('./routes/main')(app);
var server=app.listen(3000,function(){
    console.log("We have started our server on port 3000");
});

main.js

module.exports=function(app){
    app.get('/', function(req,res){
        res.render('index',{title:"Home page"});
    });
    app.get('/calendar',function(req,res){
        res.render('calendar',{"foo": "bar"});
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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