I am trying to access the things that I send from req.body in nodejs but it always comes as undefined I have tried using body-parser still it shows undefined.
Here is my code:
const express = require ('express');
const app = express();
var bodyParser = require("body-parser");
var cors = require('cors');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(cors());
app.post('/api/parts', (req, res) =>{
console.log('In app.post with id:'+ req.body.id + ' name:'+ req.body.name); // shows undefined in id and name
const part= parts.find(c=>c.id === parseInt(req.body.id));
if(!part) {
console.log('part not found and to be inserted/pushed -current lenght:'+ parts.length);
const p= { id:parseInt(req.body.id), name:req.body.name};
parts.push(p);
console.log('parts lenght:'+ parts.length);
console.log(parts);
res.send(parts[parts.length-1])
}
else {
console.log('Part with ID '+ req.body.id+ ' exists already');
res.status(404).send('Part with ID '+ req.body.id+ ' exists already')
}
})
Here is my postman Body:
{
"id":1,
"name":"abcd"
}
Related
i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);
When ran, I get an error saying:
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
the code:
const express = require("express");
const app = express();
const https = require("https");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",function (req,res) {
res.sendFile(__dirname + "/public/index.html")
app.use(express.static('public'));
})
app.post("/",function(req,res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const data = {
members:{
email_address: email,
status:"subscribed",
merge_fields:{
FNAME:firstName,
LNAME:lastName
}
}
}
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/";
const options = {
method:"POST",
auth:"sudolake:api_key"
}
const request = https.request(url, options, function(response){
response.on("data",function(){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
app.listen(3000, function(){
console.log("the server is up & running");
})
I know its probably something with the "const jsonData = JSON.stringify(data);" but I don't know what, its probably really stupid, thanks for any help
GET http://localhost:5000/booksIdea/show 403 (Forbidden)
i check the token in the website https://jwt.io/ i got invalid signature so i guess why the problem came from but i ignore how to fix it
i searched abt this error and this is what i found : Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”
API GET function on front end:
import axios from 'axios'
export const ShowBooks = () => {
let token = localStorage.getItem("usertoken")
return axios.get("http://localhost:5000/booksIdea/show", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
}
backend app.js
const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
var cors = require('cors')
var bodyParser = require('body-parser')
const port = 5000
const routes = require("./routes");
const con = require('./db')
var cors = require('cors')
app.use(cors())
// database connect
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
//cookie
app.use(cookieParser())
//routes
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
here is routes
var express = require('express')
var router = express.Router()
var Controller = require('./controller')
var authController = require('./authController')
var BooksIdeaController = require('./BooksIdeaController')
router.post('/register',Controller.register);
router.post('/login',authController.login);
router.post('/booksIdea/:id',authController.verify,BooksIdeaController.addComment)
router.post('/booksIdea/addbook',authController.verify,BooksIdeaController.addBookIdea)
router.get('/booksIdea/show',authController.verify,BooksIdeaController.showBookIdea)
router.put('/booksIdea/edit/:id',authController.verify,BooksIdeaController.UpdateBookIdea)
router.delete('/booksIdea/delete/:id',authController.verify,BooksIdeaController.DeleteBookIdea)
module.exports = router;
authController
const con = require('./db');
var bcrypt = require('bcrypt');
let jwt = require('jsonwebtoken');
const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
module.exports.login=function(req,res){
var username=req.body.name;
var password=req.body.password;
con.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
bcrypt.compare(password, results[0].password, function (err, result) {
if (result == true) {
jwt.sign({user:results},'configSecret',(err,token)=>{
res.json({
token:token
})
});
// res.json({
// status:true,
// message:'successfully authenticated'
// })
} else {
res.json({
status:false,
message:"username and password does not match"
});
}
});
}
else{
res.json({
status:false,
message:"username does not exits"
});
}
}
});
}
module.exports.home=function(req,res){
res.send('hello');
}
//////
// if(password==results[0].password){
// }else{
//
// }
module.exports.verify = function verifyToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers['authorization'];
// Check if bearer is undefined
if(typeof bearerHeader !== 'undefined') {
// Split at the space
const bearer = bearerHeader.split(' ');
// Get token from array
const bearerToken = bearer[1];
// Set the token
req.token = bearerToken;
// Next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}
How can I fix this error? thank you in advance for your help
Check your localstorage localStorage.getItem("usertoken")
Your token can be:
missing or undefined
incorrect token - probably a typo
I was trying to make an axios post request to an express server and I receive that Error: Request failed with status code 404 at createError. Postman says Can Not POST. I don't know what could be wrong, i'm new in all this, so all the help it's good, thanks.
Axios and Express server are from 2 different link. They are google cloud function.
Thanks for the help
Axios Post Request :
exports.notification = (req, res) => {
var axios = require('axios');
var https = require('https');
var bodyParser = require('body-parser');
var config = {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Type' : 'text/html',
'Content-Type' : 'application/json' }
};
var info = {
ids:[req.body.id,req.body.id1],
type: req.body.type,
event: req.body.action,
subscription_id: req.body.subid,
secret_field_1:null,
secret_field_2:null,
updated_attributes:{
field_name:[req.body.oname,req.body.nname]}
};
var myJSON = JSON.stringify(info);
return axios.post('https://us-central1-copper-mock.cloudfunctions.net/api/notification-example', myJSON)
.then((result) => {
console.log("DONE",result);
})
.catch((err) => {
console.log("ERROR",err);
console.log("Error response:");
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
})
};
Express Server
const express = require ('express');
const https = require ('https');
const bodyParser = require ('body-parser');
const app = express();
const port = 8080;
// ROUTES
var router = express.Router(); // get an instance of router
router.use(function(req, res, next) { // route middleware that will happen on every request
console.log(req.method, req.url); // log each request to the console
next(); // continue doing what we were doing and go to the route
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/',require ('./Routers/API/home'));
app.use('/leads',require ('./Routers/API/leads'));
app.use('/people',require ('./Routers/API/people'));
app.use('/companies',require ('./Routers/API/companies'));
app.use('/opportunities',require ('./Routers/API/opportunities'));
app.use('/projects',require ('./Routers/API/projects'));
app.use('/tasks',require ('./Routers/API/tasks'));
app.use('/activities',require ('./Routers/API/activities'));
app.use('/notification-example',require ('./Routers/API/notification_example'));
app.use('/', router); // apply the routes to our application
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Listening ' + port);
module.exports={
app
};
Notification Route
const express = require('express');
const router = express.Router();
//const notification_example = require('../../Notification');
router.get('/', function(req, res) {
console.log('DATA',JSON.parse(res.data));
console.log('BODY',JSON.parse(res.body));
});
module.exports = router;
i'm new to the forum and i've been doing a project for my university and i got a problem with my post request. Can anyone help me with this?
I'm using express and mongo.
Here's my code:
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var methodOverride = require('method-override');
var app = express();
app.use(cors());
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
mongoose.connect('mongodb://localhost/futbol', { useMongoClient: true });
require('./Modelos/partidos.js');
app.use(require('./Rutas'));
var router=express.Router();
app.use(router);
app.listen(port, () => {
console.log('We are live on ' + port);
});
index.js
var router=require('express').Router();
router.use('/api/partidos', require('./partidos'));
module.exports=router;
partidos.js
var mongoose = require('mongoose');
var router = require('express').Router();
var bodyParser = require('body-parser');
var Partido = mongoose.model('partido');
// GET ALL
router.get('/', (req, res, next) => {
Partido.find({})
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// GET BY ID
router.get('/:_id', (req, res, next) => {
let _id = req.params._id
Partido.findById(_id)
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// POST PARTIDO
router.post('/', (req, res, next) => {
var _id = req.body._id;
var id_equipo1 = req.body.id_equipo1;
var nombre_equipo1 = req.body.nombre_equipo1;
var id_equipo2 = req.body.id_equipo2;
var nombre_equipo2 = req.body.nombre_equipo2;
var fecha_inicio = req.body.fecha_inicio;
var hora_inicio = req.body.hora_inicio;
res.send("post _id: "+_id+" - id_equipo1: "+id_equipo1+" - nombre_equipo1 "+nombre_equipo1+" - id_equipo2 "+id_equipo2+" - nombre_equipo2 "+nombre_equipo2+" - fecha_inicio "+fecha_inicio+" - hora_inicio "+hora_inicio);
});
module.exports=router;
The POST method that is throwing an error is in partido.js
I'm also using RestEasy to make my post request with this parameters:
Url: http://localhost:3000/api/partidos
Method: POST
Headers: Content-Type: application
Body:
{
"_id" : "2",
"id_equipo1" : "4",
"nombre_equipo1" : "Independiente",
"id_equipo2" : "5",
"nombre_equipo2" : "River",
"fecha_inicio" : "10/10/17",
"hora_inicio" : "21:00:00"
}
This is the result:
{
post _id: undefined,
id_equipo1: undefined,
nombre_equipo1: undefined,
id_equipo2: undefined,
nombre_equipo2: undefined,
fecha_inicio: undefined,
hora_inicio: undefined
}
Thanks in advance!