在ExpressJS中创建一个简单的待办事项列表

时间:2018-07-19 08:03:49

标签: javascript node.js express

我正在尝试使用expressJS创建一个简单的待办事项清单。现在,我只想显示我拥有的一些硬编码的待办事项。但是我似乎找不到我做错了什么。我是一个初学者,希望能对您有所帮助。谢谢。

我已经为文件夹完成了npm init和npm install express

我的代码-

server.js文件

const express=require('express')
const srv=express();


srv.get('/todos',(req,res)=>{

    const todosroute=require('./routes/todos')
    srv.use('/todos',todosroute)
    res.send(todos)
})

srv.listen(2323)

todos.js文件

const serv=require('express').Router()
let todos=[
    {name:"Eat Kiwi's", time:"12pm"},
    {name:"Clean the room", time:"1pm"},
    {name:"Wash the car", time:"3pm"},
    {name:"Go to NSIT", time:"5.30 pm"},

]
route.get('/',(req,res,)=>res.send(todos))
route.get('/:id',(req,res)=>res.send(todos[req.params.id]))
module.exports=route

如果您能解释这个错误,那就太好了!

我在url-> ** {http://localhost:2323/todos

上收到此错误
This site can’t be reached
localhost refused to connect.
Search Google for localhost 2323 routes todos
ERR_CONNECTION_REFUSED

还有url-> http://localhost:2323/routes/todos

上的此错误
 This site can’t be reached
    localhost refused to connect.
    Search Google for localhost 2323 routes todos
    ERR_CONNECTION_REFUSED

文件结构-> ![Ive just put route folder as a comment mentioned and put todos.js in it ] 1

//已解决:D

2 个答案:

答案 0 :(得分:1)

我立即在您的todo.js中看到的一个问题是您正在导出route但使用serv-

const serv=require('express').Router()
let todos=[
    {name:"Eat Kiwi's", time:"12pm"},
    {name:"Clean the room", time:"1pm"},
    {name:"Wash the car", time:"3pm"},
    {name:"Go to NSIT", time:"5.30 pm"},

]
route.get('/',(req,res,)=>res.send(todos))
route.get('/:id',(req,res)=>res.send(todos[req.params.id]))
module.exports=route

将其更改为-

const route=require('express').Router()
    let todos=[
        {name:"Eat Kiwi's", time:"12pm"},
        {name:"Clean the room", time:"1pm"},
        {name:"Wash the car", time:"3pm"},
        {name:"Go to NSIT", time:"5.30 pm"},

    ]
    route.get('/',(req,res,)=>res.send(todos))
    route.get('/:id',(req,res)=>res.send(todos[req.params.id]))
    module.exports=route

对于server.js,请尝试-

const express=require('express')
const srv=express();
const todosroute=require('./routes/todos');

srv.use('/todos',todosroute);

srv.listen(2323)

答案 1 :(得分:1)

您需要将代码更改为以下内容:

server.js文件

const express=require('express')
const srv=express();


srv.use('/todos',require('./routes/todos'))

srv.listen(2323)

todos.js文件

const serv=require('express').Router()
let todos=[
    {name:"Eat Kiwi's", time:"12pm"},
    {name:"Clean the room", time:"1pm"},
    {name:"Wash the car", time:"3pm"},
    {name:"Go to NSIT", time:"5.30 pm"},

]
serv.get('/',(req,res,)=>res.send(todos))
serv.get('/:id',(req,res)=>res.send(todos[req.params.id]))
module.exports=serv

server.js中的问题是您要发送todos变量,该变量在另一台路由器中描述。您应该改用为所有/todos路由创建的路由器

todos.js文件中的问题是您将路由器存储在serv常量中,但是使用了未定义的route变量。