Node JS - can't send data from Postman - node.js

I solved it, it was a problem with req.body empty
==
I trying to test this route but the data I send is not received. I tried Postman and a VC extension, same problem.
I send this data and I expected it to be available in req.body
{
"username": "OPK"
}
http://prntscr.com/tn722o
And header is set correctly to application/json
http://prntscr.com/tn74on
I do however get this error when I try rest client extension:
Header name must be a valid HTTP token ["{"]
app.js
const express = require("express")
const app = express()
const userRouter = require("./routes/userRoute")
const dotenv = require("dotenv")
dotenv.config()
mongoose.connect(process.env.CONNECTIONSTRING, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
app.use(express.urlencoded({ extended: false }))
// app.use(express.json())
app.use("/user", userRouter)
app.listen(process.env.PORT)
useRoute.js:
const express = require("express")
const router = express.Router()
const userController = require("../controllers/userController")
router.post("/signup", userController.signUp)
module.exports = router
userController.js
const mongoose = require("mongoose")
const userModel = require("../models/userModel")
exports.signUp = (req, res) => {
const { username, email, password, passwordAgain } = req.body
return res.status(422).json({ username: username })
}

I suggest you to update your Postman to the latest version and install it as a separate application, not as extension for Chrome.
To check if your server method works in general you can send this request via curl:
curl --location --request POST 'http://localhost:5000/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{"username": "OPK"}'

You might need to use body-parser with Express.js to handle POST requests, that is if you're not using express#4.16.0 or greater.
npm instal --save body-parser
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Related

req.cookies is null and I don't know why

I've looked at a few previous stack overflow posts but can't figure out why this is happening.
I have included cookie parser before all my routes and the cookie is in the browser. For some reason I just can't access it.
const cookieParser = require("cookie-parser");
const cors = require("cors");
const AppError = require("./utils/appError");
const globalErrorHandler = require("./controllers/errorController");
const dishRouter = require("./routes/dishRoutes");
const userRouter = require("./routes/userRoutes");
const orderRouter = require("./routes/orderRoutes");
const imageRouter = require("./routes/imageRouter");
const app = express();
app.use(cookieParser());
app.enable("trust proxy");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.options("*", cors());
ROUTES...
Here is how I am accessing the req.cookies
First I do an axios call
axios({
method: "patch",
url: `http://localhost:8080/api/v1/users/me`,
data: this.state,
})
Then it goes through this middleware
router
.route("/me")
.patch(authController.protect, userController.updateProfile)
In authController.protect I do the following
try {
//1) Getting token and check if it exists.
let token;
if (
//POSTMAN
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}
console.log(`TOKEN: ${token}`);
console.log(req.cookies);
The console.log right above gives null.
I faced a similar issue with my code where I was getting null when checking req.cookies. I used express for my node.js files and I followed the explanations from the following links:
http://expressjs.com/en/resources/middleware/cors.html
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
So from server side I added configuration to cors() and set credentials: true and on client side from my fetch() request I added credentials: 'include' and this gave me access to the cookies on my browser. My fetch() request was making use of the PUT method.

Retrieve body data node express

I'm trying to retrieve body data but I only receive undefined on my terminal, dunno how/where to retrieve the "email". I've googled it a bit but can't seen to find the answer.
Here's the app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
//routes which should handle request
app.post("/orders", (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
And here's the server.js file:
const http = require('http');
//import app.js file
const app = require('./app');
//define port to be used
const port = process.env.PORT || 3100;
const server = http.createServer(app);
server.listen(port, () =>{
//print a message when the server runs successfully
console.log("Success connecting to server!");
});
I want to receive the "name" data and use it in a function to return a json. I'm using postman to send post requests with one key only, named "email". Postman receives the Json test data "Orange, Apple, Banana" that I have coded, though.
For x-www-form-urlencoded your example should work fine (just choose it in Postman under the body tab).
If you want to POST data (e.g. with files) as multipart/form-data you can install the multer middleware and use it in your app: app.use(multer().array())
// File: app.js
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer().array());
//routes which should handle request
app.post("/orders", async (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
This works with:
curl --location --request POST 'localhost:3100/orders' \
--form 'email=john#example.com'
and
curl --location --request POST 'localhost:3100/orders' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'email=john#example.com'

Problems POSTing json to Node/Express server from Axios/React

I'm current working on a web application using Node.js with Express in the back-end and React.js in the front end. In attempting to post user data to the Node server, through axios, I am running into an issue. When I make a post with the x-www-form-urlencoded content type, the front end will post to the server but the entire JSON of the posted data appears in the key field of the first element. When I change the content type to json it stops posting anything from the front end. I have tried cUrling to the server, and curling a JSON post will get accepted by the server.
React code to post to server
handleSubmit()
{
var form=this;
var axiosConfig = {
headers: {
'content-type': 'application/json; charset=utf-8'
}
}
axios.post('http://localhost:8080/api/login/', {
'username': form.state.username,
'password': form.state.password
}, {headers: {'content-type': 'application/json'}});
};
Server code for api endpoint
//From server.js
const express=require('express');
const session=require('express-session');
const bodyParser=require("body-parser");
const path = require('path');
var login = require('./routers/login')
var port = process.env.PORT || 8080;
var app=express();
app.use(session({'secret': 'thealphabetbackwardsiszyxwvutsrqponmlkjihgfedcba'}));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
//...
app.use('/api/login', login);
//from login.js
/* Router for login system
When user attempts to log in, check their credentials
If the user successfully logs in, create a session
If user enters invalid credentials prompt them
*/
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const user = require("./../models/UserSchema")
mongoose.connect('mongodb://localhost/newt');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res)
{
console.log("Test");
})
router.post('/', function(req, res)
{
console.log(req.body);
res.end();
})
// To create test user use path localhost:8080/api/login/testing
router.get('/test', function (req, res)
{
var db = mongoose.connection;
var test = new user({
username: "joesephschomseph",
email: "testUser#test.com",
fname: "Joe",
lname: "Schmoe"
})
test.save();
console.log("Created test user!");
});
module.exports = router
npm install --save const body-parser
in app.js include const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
remove the single quotes from your 'username' and 'password'
console.log(req.body);

Post request sent by CURL gets parsed correctly but when sent from postman, I get undefined data

I am learning Node.js as a result I am setting up a authentication service. I have an issue parsing the body from post request.
This is my index.js file
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const port = 3000
app.use(express.json());
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.password;
console.log("User name = "+username+", password is "+password);
res.end("yes");
});
This is printed on the console:
bash-3.2$ node index.js
App running on port 3000.
Username = undefined, password is undefined
But when i use CURL
curl --data "username=Jerry&password=jerry#example.com" http://localhost:3000/login
It works. Don't know why?
You have to change the postman header settings. Try changing the header content type value to application/json and change body to raw.

ExpressJs request body is empty

I have an express app at localhost:5000 and a react app at localhost:3000.
I am calling it via
fetch(`${backendUrl}/charge`, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json"
},
body: {
stripeToken: token,
chargeAmount: this.state.donationAmount
}
})
And responding with
function route(req, res) {
console.log(req.body);
}
Server should be properly configured to work with CORS, but the body is still empty.
//configure env variables
require("dotenv").config();
//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
//import route functions
const StripeRoute = require("./StripeRoute");
//setup app
const app = express();
const port = process.env.PORT || 5000;
//setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes
//Connect functions to API routes
app.post("/charge", StripeRoute);
module.exports = app;
According to the documentation, the body option should be one of a few specific types, Object not being one of them.
Try using a JSON string:
body: JSON.stringify({
stripeToken: token,
chargeAmount: this.state.donationAmount
})
EDIT: because you're using no-cors, you can't set Content-Type application/json. Instead, you need to generate a URL-encoded string and set Content-Type to application/x-www-form-urlencoded (because no-cors will only work using "simple headers", as explained here and further).

Resources