json - 使用express在node js中输出JSON对象

标签 json node.js express

这是我第一次使用Node,我使用的是express框架。我试图在“日历”页面上输出一个 json 对象(在 main.js 中看到)。当我运行路由器(main.js)时,出现此错误:错误:ENOENT,没有此类文件或目录 '/Users/Macbook/Desktop/node/views/('calendar.ejs')'

基本上我想将 main.js 中定义的 JSON 对象输出到我的 html 文件中。有人可以向我解释一下为什么服务器找不到日历文件吗?它可以找到index.ejs,但不能找到calendar。这是实现我想要实现的目标的正确方法吗?

下面是我设置的目录结构:

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

这是我的 server.js 代码:

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");
});

这是我的 main.js 代码:

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"});
    });
}

最佳答案

只是猜测。

首先,使用 require('./routes/main')(app); 设置 GET/calendar 路由。

然后使用 app.set('views',__dirname + '/views'); 覆盖 GET/calendar 路由。

您需要选择 GET/calendar 是返回呈现的 HTML 还是 JSON 数据。

关于json - 使用express在node js中输出JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109421/

相关文章:

node.js - Express 4 路线设置

javascript - 没有正文解析器的 Express 输入 JSON 在哪里?

node.js - Express 和子域(无静态文件)

json - 如何将 JSON+Patch 与 BackboneJS 嵌套模型/集合一起使用?

node.js - Azure Function Runtime 版本 : 2. 0.11888.0(测试版)变得无法连接到 cosmosDB

ajax - Chrome : GET request cancelled for CORS HTTPS request

node.js - Browserify - bower vs npm Node 模块

node.js - Azure Bot Framework V4 (NodeJS) - LUIS 识别器返回错误?

javascript - 从 angularjs 访问 json 数据

javascript - 服务不会以 Angular 方式将数据返回到 Controller