I'm getting the error as 404 not found while trying to post data using postman in chrome.Any kind of help would be highly appreciated.
I'm doing this application from the following link :https://www.youtube.com/watch?v=wtIvu085uU0
here is my code.
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);
Getting the following error in postman:
<!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"
}
router.post('./contact' should be router.post('/contacts
Related
I am trying through node js, express and mongoose to create a way to add the same mongoose Schema more than one time I want to use a trigger button. I have to restart the server to add more to the DB.
Later on I want to change it through a counter but first I need to get this working.
I am trying to solve it on my own but I got stuck, thank you for your help !
the app.js I use as server.
/app.js
const express = require('express');
const { default: mongoose } = require('mongoose');
const path = require('path');
const db = require("./database");
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static('DB'));
app.use('/Dev', express.static(path.join(__dirname, 'Dev', 'public')));
//Export function to new a .js file
var ClickyClicky = new mongoose.Schema({
name: {
type: String,
require: true
}},
{
timestamps: true, //time
}
);
var Clicky = mongoose.model('Click', ClickyClicky, 'clickystore');
var Clicks = new Clicky({ name: 'Test' });
//Export function to new a .js file
//Save button trigger.
app.post('/test', (req, res) => {
Clicks.save(function (err, book) {
if (err) return console.error(err);
console.log(book.name + " saved to bookstore collection.");
});
});
//Save button trigger.
app.post('/alfa', (req, res) => {
Clicks.save(function (err, name) {
if (err) return console.error(err);
console.log(name.name + " saved to name collection.");
});
});
// // 404 page
app.all('*', (req, res) => {
res.status(404).send('<h1>404, Page not found !</h1>');
});
app.listen(5000, () => {
console.log('Server started at http://localhost:5000');
});
/client.js
console.log('Client code running');
const testButton = document.getElementById('Button');
testButton.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/test', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
const testButton2 = document.getElementById('Button2');
testButton2.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/alfa', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Button">Click me for a test!</button>
<button id="Button2">Click me for a test1!</button>
</body>
<script src="./Dev/Client.js"></script>
</html>
\database.js
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGOOB_URI, () => {
console.log("Connected to MongoDB");
});
I solved my issue with adding, unique: false to my mongoose schema and deleted the old input from the BD
i am testing this url==> (http://localhost:8800/api/users/634ed4af41fb0169e999deb2/follow) on
postman, it works in case of without having (/follow), But when i use this url every time i get this error=====>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot PUT /api/users/634ed4af41fb0169e999deb2/follow%0A</pre>
</body>
</html>
Below i am getting issue in using // app.use('/api/users',userRoutes)//. This will call the router present in the users.js
index.js
const express= require("express");
const app=express();
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const userRoutes=require("./routes/users")
const authRoutes=require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL,
{useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
console.log("connected to database");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
//cutom middleware for Routing
app.use('/api/users',userRoutes);
app.use('/api/auth',authRoutes);
app.listen(8800,()=>{
console.log("backend server running");
})
here in user.js controller are not able to log the console present at the top position.
user.js
const router=require("express").Router();
const bcrypt=require('bcrypt');
const User = require("../models/User");
//follow user
router.put("/:id/follow", async (req , res)=>{
console.log(req.body.userId === req.params.id.trim());
if(req.body.userId !== req.params.id){
try {
const user= await User.findById(req.params.id);
const currentUser= await User.findById(req.body.userId);
if(!user.followers.includes(req.body.userId)){
await user.updateOne({$push:{followers:req.body.userId}});
await currentUser.updateOne({$push:{followings:req.params.id}});
res.status(200).json("user has been follwed")
}else{
res.status(403).json('you all ready followed')
}
} catch (error) {
res.status(500).json(error)
}
}
else{
res.status(403).json("you cant follow yourself")
}
})
I am getting this error while running Node.js Server:
CastError: Cast to ObjectId failed for value " 5f04cc85d5db3f0d582fb51a" at path "_id" for model "Blog"
I have tried all possible method I know to do this but it is not working.
This is the code from blogapp.js
Following the RESTful Routes, I want to show more details about a particuler post when the Read more is clicked. But it was not working so I decided to print the error and this is what it is showing : Casterror: .....
var express = require('express');
app = express();
bodyParser = require('body-parser');
mongoose = require('mongoose')
// APP CONFIG
mongoose.connect('mongodb://localhost/restful_blog_app', { useNewUrlParser: true, useUnifiedTopology: true});
app.set('view engine', 'ejs');
app.use(express.static('Public'));
app.use(bodyParser.urlencoded({extended:true}))
// MONGOOSE/MODEL CONFIG
var blogSchema = new mongoose.Schema({
title:String,
image:String,
body: String,
created :{type: Date, default: Date.now}
});
var Blog = mongoose.model('Blog', blogSchema)
// RESTFUL ROUTES
app.get('/', (req,res) => {
res.redirect('/blogs')
})
// INDEX ROUTE
app.get('/blogs', (req,res) => {
Blog.find({}, (err, blogs) => {
if(err){
console.log(err);
}else{
res.render('blogindex', {blogs:blogs})
}
})
});
// NEW ROUTE
app.get('/blogs/new', (req,res) => {
res.render('blognew')
});
// CREATE ROUTE
app.post('/blogs', (req,res) => {
// create blog
Blog.create(req.body.blog, (err, newBlog) => {
if(err){
res.render('new');
}else{
// then redirect to the index
res.redirect('/blogs')
}
});
});
// SHOW ROUTE
app.get('/blogs/:id', (req,res) => {
Blog.findById(req.params.id , (err, Blog)=>{
if(err){
res.send(` ${err}`);
}else{
res.render('blogshow', {blog: Blog})
}
});
});
app.listen('5000', ()=>{
console.log("Blog Server running on port 5000");
});
I don't know where I am getting it wrong
This is the code from blogshow.ejs
<%- include ('partials/blogheader') %>
<div class="ui main text container segment">
<div class="ui huge header"> <%= blog.title %> </div>
</div>
<%- include ('partials/blogfooter') %>
The problem is that your req.params.id contains a leading whitespace:
" 5f04cc85d5db3f0d582fb51a" but it should be "5f04cc85d5db3f0d582fb51a"
Mongoose does not trim any values and obviously cannot cast this value to an ObjectId.
What you could do is Blog.findById(req.params.id.trim()) in order to make sure the whitespace is removed and/or make sure in the client-code that you're not sending the value containing whitespaces.
I'm trying to create a CRUD REST API in NodeJS, Express, and Mongodb.
I did something to break all my routes where they no longer return responses. No errors, nothing in the console, etc. I'm not sure what happened, I had it working before. Through just some console.logs I figured out it was freezing whenever it interfaced with the database.
Now, when I send a post request in Postman, it just hangs with 'Loading request'. I'm sending my request as a raw JSON in the body and a content type of application/json; charset=UTF-8 in the header.
{"username":"zezimaUsername","rsn":"Zezima","avatar":"http://secure.runescape.com/m=avatar-rs/Zezima/chat.png"}
They seem to all be hanging once they interact with Mongodb. I have Mongodb running locally with the mongod --port 27017 and created my database with two collections (user and posts) in Mongodb Compass.
I setup my db in a db.js file...
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/my-group';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));
module.exports = db;
And start my app with my server.js...
var express = require('express');
var api = require('./api');
var app = express();
app.use(express.json());
app.use('/api', api);
//Error handling, don't return stack trace to user, log in console.
app.use(function (err, req, res, next){
console.log(err.stack);
res.status(500).send('Something went wrong, internal server error.');
});
app.listen(3000, function(){
console.log("Listening on port 3000");
});
And define my routes in my api.js file...
var express = require('express');
var router = express.Router();
var User = require('./db/models/User');
var Post = require('./db/models/Post');
router.post('/register', function(req, res){
var user = new User(req.body);
user.save()
.then(function(item){
res.status(200).send({message: "User successfully created.", status: 200});
})
.catch(function(err){
res.status(400).send({message: "User failed to save to database", status: 400});
});
});
router.get('/user/:username', function(req, res){
var query = User.findOne({"username": req.params.username});
query.exec(function(err, user){
if(user === null){
res.status(404).send({message: "User not found", status: 404});
}else{
res.status(200).send(user);
}
});
});
router.post('/create_post', function(req, res){
var post = new Post(req.body);
post.save()
.then(function(item){
res.status(200).send({message: "Post successfully created.", status: 200});
})
.catch(function(err){
console.log(err);
res.status(400).send({message: "Post failed to save to database", status: 400});
});
});
router.get('/post/id/:id', function(req, res){
var query = Post.findOne({"_id":req.params.id});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
router.get('/post/boss/:boss', function(req, res){
var query = Post.find({"boss":req.params.boss});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
module.exports = router;
And just to be complete...my models look like...
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username:{
type: String,
required: true
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
posts:[{
type: Schema.Types.ObjectId,
ref: 'posts'
}]
});
var user = mongoose.model('users', userSchema);
module.exports = user;
and Post.js
var mongoose = require('mongoose');
var shortid = require('shortid');
var Schema = mongoose.Schema;
var postSchema = new Schema({
_id:{
type: String,
default: shortid.generate
},
username:{
type: Schema.Types.ObjectId,
ref: 'users'
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
boss:{
type: String,
required: true
}
});
var post = mongoose.model('posts', postSchema);
module.exports = post;
I'm not sure what's happening, I keep reading a bunch of various tutorials and the documentation but I'm just not seeing the issue I'm having.
You have not required your db.js file in your server.js file.
Require it after var express = require('express');
let db = require("./db");
Then it will work fine.
I am creating creating a bookstore demo app in Node.js. I have ran into a little situation with the POST request for creating a genre. I've setup so the name of the genre must be required if not don't insert it to the database. But when I use Postman to POST to the url localhost:3000/api/genres with the JSON
{
"name": "TEST"
}
It throws an error
{
"error": "Genre validation failed"
}
When I remove the required field in the genreSchema it works but the name of the genre doesn't appear. Here is my code
Code:
genre.js
var mongoose = require("mongoose");
// Create a schema for genre
var Schema = mongoose.Schema;
var genreSchema = Schema({
name:{
type: String,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model("Genre", genreSchema);
// Methods
// get genres
module.exports.getGenres = function(callback, limit) {
Genre.find(callback).limit(limit);
};
// add a new genre
// TODO: Not working in Postman ValidationError
module.exports.addGenre = function(genre, callback) {
Genre.create(genre, callback);
};
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Genre = require('./models/genre');
var Book = require('./models/book');
// Connect to mongoose
mongoose.connect("mongodb://localhost/bookstore");
var db = mongoose.connection;
app.get("/", function(req, res){
res.json({ error: "Please use /api/books or /api/genres" });
});
// GET /api/genres
app.get('/api/genres', function(req, res){
Genre.getGenres(function(err, genres){
if(err) {
res.json({error: err.message})
}
res.json(genres);
});
});
app.post('/api/genres', function(req, res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
if(err) {
res.json({
error: err.message
})
}
res.json(genre);
});
});
// GET /api/books
app.get('/api/books', function(req, res){
Book.getBooks(function(err, books){
if(err) {
res.json({error: err.stack})
}
res.json(books);
});
});
// GET /api/book/:id
app.get('/api/book/:_id', function(req, res){
Book.getBookById(req.params._id, function(err, book){
if(err) {
res.json({error: err.message})
}
res.json(book);
});
});
app.listen(3000, function(){
console.log("Running on port 3000!")
});
Have you tried console.log(req.body); inside your post route? I don't think you've setup body-parser as middleware so req.body is coming in empty and therefore not sending anything to your Genre.addGenre method.