使用平均堆栈应用程序时404未找到错误

时间:2017-11-15 17:06:14

标签: node.js mongodb angular postman

我在尝试使用chrome中的邮递员发布数据时发现错误为404.Any的帮助将非常受欢迎。

我通过以下链接执行此应用程序:https://www.youtube.com/watch?v=wtIvu085uU0

这是我的代码。 app.js

//importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();
const route=require('./router/route');

//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlistapp');

//on connection
mongoose.connection.on('connected',()=>{
console.log('successfully connected to database mongodb @27017');

});

mongoose.connection.on('error',()=>{

    if(err)
    {

        console.log('Error in database connection:'+err);
    }


    });


//port number
const port=3000;



//adding middleware-cors
app.use(cors());

//bodyparser
app.use(bodyparser.json());

//adding routes
app.use('/api',route);

//static files
app.use(express.static(path.join(__dirname,'public')));

//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});


app.listen(port,()=>{
console.log('serve started at'+port);

});

route.js

const express=require('express');
const router=express.Router();
const contact=require('../models/contacts');


//retrieving contacts
router.get('/contacts',(req,res,next)=>{
contact.find(function(err,contacts){
    res.json(contacts);
})

});



//retrieving data
router.get('/contacts',(req,res,next)=>{
res.send('Retrieving the contacts list');

});

//add contacts
router.post('./contact',(req,res,next)=>{
let newContact=new contacts({
first_name:req.body.first_name,
last_name:re.body.last_name,
phone:req.body.phone

})

newContact.save((err,contact)=>{
if(err){
res.json({msg: 'Failed to add contact'});

}
else{

    res.json({msg: 'contact added successfully'});

}
})

});

//delete contacts
router.delete('./contact/:id',(req,res,next)=>{
    contact.remove({_id:req.params.id},function(err,result){
if(err)
{
    res.json(err);
}
else{

    res.json(result);
}
    })
    });


module.exports=router;

contacts.js

const mongoose=require('mongoose');

const ContactSchema=mongoose.Schema({
first_name:{
    type:String,
    required:true
},
last_name:{

    type:String,
    required:true
},
phone:{

        type:String,
        required:true
    }

});

const contact=module.exports=mongoose.model('contact',ContactSchema);

在邮递员中收到以下错误:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>Cannot POST /api/contacts</pre>
    </body>
</html>

The following is the json data i'm trying to post:

    {
        "first_name":"anand",
        "last_name":"reddy",
        "phone":"1234567813"



    }

1 个答案:

答案 0 :(得分:0)

ngOnChanges()应为router.post('./contact'