First off let me say sorry if the title of the question confused anyone reading my question. I didn't know how to best word my question. The issue I'm having is when I try to send a get request from my axios instance to my express instance. When I send data from axios, I have my object showing all the data it needs but when I try to utilize that data in express using req.params.email the value its holding is :email heres my code:
Client/Axios
checkEmail (data) {
return http.get('/users/:email', data)
},
Value of 'data' Object
{email: 'ThisIs#MyEmail.Org'}
Server/Express
router.get('/users/:email', function (req, res) {
console.log(req.params.email)
const data = User.find({ email: req.params.email })
return res.sendStatus(200).json(data)
})
Server Console Log
{ email: ':email' }
As a side note I have tried to just use req.params but it returns the same thing. If anyone can point out what I'm doing wrong I would greatly appreciate it!
This code will works.
You needs to switch from hard code data
to your const data = User.find({ email: req.params.email })
From
const data = {
email: 'test#gmail.com',
first_name: 'Tom',
last_name: 'Cruise'
}
To
const data = User.find({ email: req.params.email })
server.js
const express = require("express")
const axios = require('axios')
const cors = require("cors")
const app = express()
app.use(cors())
app.get("/users/:email", async (req, res) => {
console.log("params", req.params);
// const data = User.find({ email: req.params.email })
const data = {
email: 'test#gmail.com',
first_name: 'Tom',
last_name: 'Cruise'
}
res.status(200).json(data);
});
app.listen(3000, () => { console.log("Listening on :3000") })
client.js
const axios = require('axios')
const checkEmail = async (data) => {
try {
const response = await axios.get(`http://localhost:3000/users/${data}`);
return Promise.resolve(response.data)
} catch (error) {
return Promise.reject(error)
}
};
checkEmail('ThisIs#MyEmail.Org')
.then(result => {
console.log('user is : ' + JSON.stringify(result))
})
.catch(error => {
console.log(error.message)
});
Install dependencies
npm install express axios cors
Run first server
node server.js
Run second client
node client.js
Result at server
Result at client
Related
[err_http_headers_sent]: cannot set headers after they are sent to the client
<=(Link is picture of the actual error)
I have been stuck on this issue for two weeks and the other Stack Overflow posts with this issue don't seem to resolve the issue. Hoping someone can help with what will resolve this issue. I am using ReactJS and NodeJS "express" for the backend. I get this error when testing in Postman. Does anyone know what I am doing wrong?
server.js file:
import express from 'express';
import { routes } from '../routes/index';
import { initializeDbConnection } from './db';
const PORT = process.env.PORT || 8080;
const app = express();
//This allows access the body of POST/PUT requests in our route handlers as req.body
app.use(express.json());
//Add all the routes to Express server exported from routes/index.js
routes.forEach(route => {
app[route.method](route.path, route.handler);
});
// Connect to the database, then start the server.
// This prevents from having to create a new DB
// connection for every request
initializeDbConnection()
.then(() => {
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
});
signuproute.js code
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getDbConnection } from '../src/db';
export const signUpRoute = {
path: '/api/signup',
method: 'post',
handler: async (req, res) => {
const { email, password } = req.body;
const db = getDbConnection('react-auth-db');
const user = await db.collection('users').findOne({ email });
if (user) {
res.sendStatus(409);
}
const passwordHash = await bcrypt.hash(password, 10);
//change once you figure out what info you want to store from users
const startingInfo = {
hairColor: '',
favoriteFood: '',
bio: '',
};
const result = await db.collection('users').insertOne({
email,
passwordHash,
info: startingInfo,
isVerified: false,
});
const { insertedId } = result;
jwt.sign({
id: insertedId,
email,
info: startingInfo,
isVerified: false,
},
process.env.JWT_SECRET,
{
expiresIn: '2d',
},
(err, token) => {
if (err) {
return res.status(500).send(err);
}
res.status(200).send({ token });
});
}
}
You can try to add return on your res
return res.sendStatus(409);
and
return res.status(200).send({ token });
I made an application to make push notifications and I succeeded in sending notifications. But I have a problem, which is that I want to save any notification that I send in my database,
Here is the code,
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.post("/fcm", async (req, res, next) => {
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, function (err, response) {
if (err) {
next(err);
} else {
// res.json(response);
// res.send(message.notification.body);
app.post("/notfs", async (req, res) => {
let newNotf = new NotificationModel({
name: message.notification.body,
});
newNotf = await newNotf.save();
res.send(newNotf);
});
}
});
} catch (error) {
next(error);
}
});
app.get("/notfs", async (req, res) => {
const notfs = await NotificationModel.find();
res.send(notfs);
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
Why doesn't it save notifications in the database?
Another question
Please if there is a better way than this please leave it and thank you٫
Thanks in advance
use axios package, which is recommended by nodejs official.
Its simple like jquery ajax call
I'm working on an app that assesses students algebra 1 level. I'm trying to send a string called "answers" to the database, but nothing is ever sent. I've shown the model/schema below, where basically each submission should send the answers String (it was originally an object, but I couldn't get an answer to Mongoose not persisting object so I'm just trying a string to see if it even submits a string. The user and date are submitted to the database, but there is not even an entry for the answers attribute. I've seen that the payload sent if I submit a "2" is {"results": "2"} so there's something in the request body. My response back from the server is {} so I think I'm not destructuring a prop correctly or maybe sending an object unintentionally.. Any ideas as to why no answers attribute is submitted to the database? Any help is greatly appreciated!
api/algebra1.js (route to send test results)
const express = require('express');
const router = express.Router();
var bodyParser = require('body-parser')
const bcrypt = require('bcryptjs');
const algebra1 = require('../../models/Algebra1');
const jwt = require('jsonwebtoken');
const config = require('config');
const auth = require('../../middleware/auth');
//#route POST api/auth
//#desc Algebra 1 route
//#access Private
var jsonParser = bodyParser.json();
router.post('/', [jsonParser, auth], async (req, res) => {
const { answers } = req.body;
try {
let newTest = new algebra1({
answers: answers,
user: req.user.id,
date: Date.now()
})
console.log("body is " + req.body)
await newTest.save();
res.json({ answers: answers });
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
})
module.exports = router;
Algebra1.js (model for Mongoose):
const mongoose = require('mongoose');
const Algebra1Schema = new mongoose.Schema({
answers: {
type: String
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
date: {
type: Date,
default: Date.now
}
})
module.exports = algebra1 = mongoose.model('algebra1', Algebra1Schema)
submit action (submits results to api/algebra1 route):
export const submit = (results) => async dispatch => {
try {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
console.log(results);
const body = JSON.stringify({ results });
const res = await axios.post('/api/algebra1', body, config);
dispatch({
type: QuestionActionTypes.RESET
})
dispatch(setAlert('You\;ve finished your assessment!', 'success'));
} catch (err) {
console.error(err.message);
}
}
You are sending data with results key and destructing as answer key. Where are you sending anything against answer key ? I guess you meant to submit results as answers.
const body = JSON.stringify({ answers: results });
I can't get a response from my server. I am using postman and running the following post request:
localhost:4000/users/register?email=test#gmail.com&f_name=testf&s_name=tests&password=test
It hangs for a very long time and then says:
Could not get any response
This is my code:
[user.route.js]
const express = require('express');
const userRoutes = express.Router();
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
//require User model in the routes module
let User = require('../models/user.model.js');
//Make router use cors to avoid cross origin errors
userRoutes.use(cors);
//secret
process.env.SECRET_KEY = 'secret';
//define register route
userRoutes.post('/register', (req, res) => {
const today = new Date();
const userData = {
email: req.body.email,
f_name: req.body.f_name,
s_name: req.body.s_name,
password: req.body.password,
created: today
}
//Find one user based on email, hash their password and then create a document in the collection for that user
User.findOne({
email: req.body.email
})
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
user.password = hash;
User.create(userData)
.then(user => {
res.json({
status: user.email + ' registered'
});
})
.catch(err => {
res.send('error: ' + err);
});
});
}
});
});
userRoutes.post('/login', (req, res) => {
User.findOne({
email: req.body.email
})
.then(user => {
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
const payload = {
_id: user._id,
f_name: user.f_name,
s_name: user.s_name,
email: user.email
}
let token = jwt.sign(payload, process.env.SECRET_KEY, {
expiresIn: 1440
});
res.send(token);
} else {
res.json({
'Error': 'Password Incorrect'
});
}
} else {
res.json({
'Error': 'User does not exist'
});
}
})
.catch(err => {
res.send('Error: ' + err);
});
});
module.exports = userRoutes;
[user.model.js]
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let User = new Schema({
email: {
type: String
},
f_name: {
type: String
},
s_name: {
type: String
},
password: {
type: String
},
created: {
type: String
}
}, {
collection: 'users'
});
[server.js]
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./db.js');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, {
useNewUrlParser: true
}).then(
() => {
console.log('Database is connected')
},
err => {
console.log('Can not connect to the database' + err)
}
);
app.use(cors());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var Users = require('./routes/user.route');
//make /users use routes
app.use('/users', Users);
app.listen(PORT, function() {
console.log('Server is running on Port:', PORT);
});
[db.js]
module.exports = {
DB: 'mongodb://localhost:27017/pharaohcrud'
}
I'm using Node, MongoDB, Mongoose, Vue, Express.
I'm new to Node in general so it's hard for me to give details on what i've done. Please feel free to ask any questions that you need answered to help me with issue and ill answer as thoroughly as i can :)
EDITS:
Here is the updated db.js file
module.exports = {
DB: 'mongodb://localhost:27017/pharaoh'
}
Here is the updated post request that im sending to the server through postman:
localhost:4000/users/register
[raw json request]
{
"email": "test#gmail.com",
"f_name": "test",
"s_name": "test",
"password": "test"
}
You have to send json data with your post request not query strings.
In postman, select "Body" tab and choose "raw" and from the dropdown menu select "json" format. Send your user data as Json, this will solve the issue.
Image description here
I went deleted all database-related code and retyped it, and now it works. I guess the lesson here is to always pay attention while typing code to make sure you're writing it correctly.
I have this api route function that needs updates a topic record to include a reference of post, then save the actual post record being created. Is there a better way to do what i want to do? is it possible?
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
newPost.save().then(post => res.json(post));
});
github line 33: https://github.com/wolffles/bloccit-node/blob/express/routes/api/topics.js
Question
How do you save the topic record you found and modified?
Answer
Try this out with the latest JS async await syntax.
router.post('/:id/posts', async (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
try {
await Topic.findById(req.params.id, (err, doc) => {
doc.posts.push(newPost._id);
doc.save();
});
const post = await newPost.save()
res.json(post)
} catch(err) {
res.send(err)
}
});
Let me know if this works for you.
Just save the document in the promise success of the topic return. Just like i wrote below.
Let me know if that works.
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
//now update the newPost
newPost.topicObj = topic;
newPost.save().then(post => res.json(post));
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
});