MEAN-Stack -- GET http://localhost:3000/api/test net::ERR_EMPTY_RESPONSE - node.js

I am a newbie in MEAN-Stack developing and need your help.
When I try a http get/post request using the Angular httpClient, I keep getting the following error message ERR_EMPTY_RESPONSE.
I start calling my get method within my frontend folder test.service.ts:
getTests(){
this.http
.get<{message: string, tests: TestModel[]}>('http://localhost:3000/api/test')
.subscribe((_testData)=>{
console.log(_testData);
});
}
The above used TestModel is my data model used in frontend:
export interface TestModel {
id: string;
title: string; }
Within my backend folder, my folder structure looks like in the picture attached. folder structure backend
This is how my app.js looks like (i replaced line 12, but the connection to database works).
const express = require('express')
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const test = require("./routing/test");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose
.connect(
x
)
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
//https://www.javatpoint.com/cors-in-mean-stack
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS");
next();
});
app.use("/api/test", test);
module.exports = app;
My test.js where i expect the error origin looks as follows:
const express = require("express");
const testModel = require('../models/testModel');
const router = express.Router();
router.get("",(req,res,next)=>{
const testRooms = [
{
id: "1",
title: "1"
},
{
id: "2",
title:"2"
},
]
return res.json("testMessage", testRooms);
});
module.exports = router;
And finally my backend data model:
const mongoose = require('mongoose');
const express = require("express");
const router = express.Router()
const TestSchema = mongoose.Schema({
id: {type: String, required: true, unique: true},
title: {type: String, required: true},
});
module.exports = mongoose.model('TestSchema', TestSchema);
My server.js (which refers to the app.js) should work correctly, therefore I haven't posted it here.
It seems like the http module is not able to access the node backend at all, since I get the same error message if I delete the method in the "test.js". First google result hinted that this might be a CORS issue, but I don't think that this is the case here.
I am quite lost :((
If I missed to upload or mention something, just let me know.
Thanks a lot for any help and a happy new year's eve :)

Related

How can I make an entry to MongoDB with this app?

Between my app and Postman I should be able to make an entry into MongoDB, but I get this.
TypeError: Cannot read property 'title' of undefined
This is the app.js file
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
require('dotenv/config')
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute)
app.use('/posts', () => {
console.log('This is a middleware.')
})
app.get('/', (req, res) => {
res.send('We are at home')
})
//Connect to DB
Mongoose.connect(process.env.DB_CONNECTION)
.then(() => {
console.log('connected to DB')
})
.catch(err => {
console.log(err);
});
app.listen(3000);
This is the posts.js file
const express = require('express');
const router = express.Router();
const Post = require('../models/Post')
var fs = require('fs');
router.get('/', (req, res) => {
res.send('We are at posts')
})
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({message: err });
})
});
module.exports = router;
This file is the Mongoose Schema
const { json } = require('body-parser');
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: JSON,
required: true
},
description: {
type: JSON,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
Then I'm trying to post to MongoDB, through the app with Postman
Hopefully this photo should suffice.
The app is running fine locally on port 3000 and I do believe I am connecting to the database. It seems like a format problem. I don't know if the schema needs to be in JSON somehow or a configuration of Postman needs to change, but I have tried every Postman setting and tried changing the schema to JSON. I also had the type in the Mongoose file as type: String
Add this in app.js for POST Request...
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Add that middleware on top of your routes.

MeanStack: blocked by cors on Linux(ubuntu)

I'm doing this MeanStack course and I managed to create several files with post routes along with their schemas. But the last file I created, shopping cart schema and its route is getting blocked by cors. I tried to move the path to the files where the post works but still, get blocked, thought yesterday this workaround actually worked, but today is not working anymore. I've tried even to add an extension to chrome but nothing is working. On windows I can easily disable the cors, but not on linux
app.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const postsRoutes = require("./routes/posts");
const userRoutes = require("./routes/user");
const nasaRoutes = require("./routes/nasa");
const movieRoutes = require("./routes/movies");
const shoppingCartRoutes = require("./routes/shoppingCart");
const app = express();
mongoose
.connect('mongodb+srv://icenine:qN4pI8Tuy0chs7qK#mean-robot-cluster.zyjkf.mongodb.net/Mean-Robot-Cluster?retryWrites=true&w=majority'
)
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
app.use("/api/posts", postsRoutes);
app.use("/api/user", userRoutes);
app.use("/api/nasa", nasaRoutes);
app.use("/api/movies", movieRoutes);
app.use("api/shoppingCart", shoppingCartRoutes)
module.exports = app;
the shopping cart schema
const mongoose = require('mongoose');
const shoppingCartSchema = mongoose.Schema({
dateCrated: { type: Number, required: true },
});
module.exports = mongoose.model('ShoppingCart', shoppingCartSchema);
the route:
const express = require("express");
const ShoppingCart = require("../models/shoppingCart");
const router = express.Router();
router.post("", (req, res, next) => {
const cart = new ShoppingCart({
date:req.body.date
});
console.log(req.body)
cart.save().then(createdCart => {
res.status(201).json({
message: "Cart created successfully",
cartId: createdCart._id
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
The Front End Angular (service)
createCart(){
let date={dateCreated: new Date().getTime()}
return this.http.post<{message:string, cartId:string}>('http://localhost:3000/api/shoppingCart', date)
}
Component
addToCart(product:Product){
let cartId = localStorage.getItem('cartId')
if(!cartId){
this.shoppingService.createCart()
.subscribe(result =>{
localStorage.setItem('cartId', result.cartId);
});
}//etc
}
The console error (front end)
The solution for Linux -Ubuntu is to open the terminal and simply type:
google-chrome --disable-web-security --user-data-dir=/tmp
You are trying to access your API which is on a different port and that's causing the cors issue, at least in the localhost environment.
you can use the cors package to allow cross-origin access.
...
const cors = require("cors");
...
app.use(cors());
...
If this is only a local project you can leave it as is or you can pass parameters to the cors function if you gonna publish your project to limit the origins allowed to access your API.

How to post some json data to a route in api

I've created a very simple API in NodeJs. Here is the code:
const Post = require('../models/article');
...
router.post('/contribute', (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
...
module.exports = router;
The structure of a Post is this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
articleid: String,
title: String,
content: String,
date: String,
contributor: String,
upvotes: Number,
upvoters: [String],
downvotes: Number,
downvoters: [String]
})
module.exports = mongoose.model('article', articleSchema, 'articles');
Here is server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
app.use('/api', api);
app.get('/', function(req, res) {
res.send('Server is up and running!');
})
app.listen((3000), function() {
console.log('Server listening on heroku environment port');
});
Ideally the data should come from an angular form/template but before pushing the code I wanted to test this on Postman. Here is the screenshot:
I'm getting:
Cannot POST /contribute
Please point out my mistake.
Because you are using:
app.use('/api', api)
So, make sure to use this endpoint:
localhost:3000/api/contribute
And now, it's will working fine.
I didn't notice that I'm hitting the wrong URL.
Wrong:
localhost:3000/contribute
Correct:
localhost:3000/api/contribute
This is working absolutely fine now and I'm getting correct json response from the server also.

node js express mongoose api save operation not working

I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;

Not able to update values of an Mlab document using mongoose, it is getting saved as "__v": 0

I am new to node and mongoDb,
I have a mongo db account where i created a collection called "dbTestData"
I am trying to create CRUD operation using node express mongoose and express,
and i am using postman to get post update and delete values to mlab db.
My Get call is working fine, but when i try to post values in Json like,
i am getting success message , but when i check the db it is saved as
{
"_id": {
"$oid": "5c3ad1c19bc5932f800d26f7"
},
"__v": 0
}
My app.js
const express = require('express');
const bodyParser = require("body-parser");
const mongoose=require('mongoose');
const app = express();
const dbTestData=require('./models/post')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect("mongodb://<userName>:<password>#ds221242.mlab.com:21242/kiitasklist").then(()=>{
console.log("hello");
}).catch(
()=>{
console.log("heee");
});
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT,DELETE, OPTIONS"
);
next();
});
app.post("/api/posts", (req, res, next) => {
const post = new dbTestData({
id:req.body.id,
name:req.body.name
});
post.save().then(documents=>{
console.log(post);
res.status(201).json({
message: 'Post added successfully'
});
});
});
app.get("/api/posts",(req,res,next)=>{
dbTestData.find().then(documents=>{
res.status(200).json({
message:'Posts fetched successful',
posts:documents
});
});
});
app.put("/api/posts/:id",(req,res,next)=>{
const post = new dbTestData({
_id:req.body._id,
name:req.body.name
});
dbTestData.updateOne({_id:req.params.id},post).then(result=>{
res.status(200).json({message:"update successfully"});
});
});
app.delete("/api/posts/:id",(req,res,next)=>{
dbTestData.deleteOne({_id:req.params.id}).then(documents=>{
res.status(200).json({
message:'posts fetched successful',
posts:documents
});
});
});
module.exports = app;
My Server.js
const http = require('http');
const app = require('./api/app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
My post.js where i have created the mongoose schema
const mongoose=require('mongoose');
var Schema = mongoose.Schema;
module.exports= mongoose.model("dbTestData", new Schema({}), "DbTestData");
both the get and delete works ,
But the post and put is not happening properly, it returns a success message in my console but empty value like
{
"_id": {
"$oid": "5c3ad1c19bc5932f800d26f7"
},
"__v": 0
}
is saved during POST and nothing happens during PUT.
To solve this post issue
var Schema = mongoose.Schema;
PostSchema = new Schema({
id:Number,
name: String
});
// the compile the model using mongoos model function giving the schema u created
const Post = module.exports= mongoose.model("dbTestData", PostSchema, "DbTestData");
after that in your post req do it like this
//before posting you need to require the model first
const Post = require('./models/post'); // your post.js
app.Post("/api/posts", (req, res, next) => {
const post = new Post({
id:req.body.id,
name:req.body.name
});
post.save().then(documents=>{
console.log(post);
res.status(201).json({
message: 'Post added successfully'
});
});
});
make sure you create/define your schema correctly in order to save data using it.
after that put is the same the way u did it should work fine after u define your schema correctly
and finally try this also. make sure you add these tow line the exact same way I have given in your case you have made them switched
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Resources