I am using POSTMAN to test me API calls with Node.Js.When I am sending POST request from POSTMAN to Node server it is showing null response in console.log().
const express = require('express');
const bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
router.get('/',(req,res) => {
console.log("Name:" +req.body.name);
res.end();
});
app.listen(port,(req,res) =>{
console.log("Server is running at:" +port);
});
Now, I am sending POSTMAN request at URL = localhost:3000/ and data is
Key: name and Value: John
In console it is showing error like
TypeError: Cannot read property 'name' of undefined
You have defined the request in the express framework as a get:
router.get
and you said you are sending a POST.
Change one thing or the other
You need to change your method to POST like this:
router.post('/',(req,res) => {
console.log("Name:" +req.body.name);
res.end();
});
Also you need to make a post throw POSTMAN with this options :
And you should have your result :
Related
In PHP I can fetch incoming JSON from let's say an AJAX request by calling file_get_contents('php://input'), I'm now rebuilding my API in NodeJS (TypeScript) and am looking for an equivalent to fetch incoming JSON.
Various web searches did not deliver what I was looing for, so I hope to find help here.
You can try to call the correct URL by using Axios. Following this link https://www.npmjs.com/package/axios for more.
You can use bodyparser for express and receive data via post.
let app = express();
const bodyParser = require("body-parser");
app.listen(port);
console.log('API started port' + port);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/path', "maybe cors()", function(req, res){
let data = req.body.data //data is the json you get
}
Thats the way i fetch json that gets send to the server. Hope you can make something with it.
I have been trying to use post request to insert data to the mongodb using mongoose, however I see that req.body is being shown as undefined. document is getting inserted in database, however only default object id is getting inserted.
This is how I send request to Postman
{
name:"wewe",
price:43}
//Post.js
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/tutorialkart");
const productSchema = mongoose.Schema({
name: String,
price: Number
});
module.exports = mongoose.model('Groduct', productSchema);
//app.js
var express = require('express')
var bodyParser = require('body-parser')
var Post = require('./Post')
var app = express()
app.use(bodyParser.json())
app.post('/api/posts', function (req, res, next) {
var post = new Post({
name: req.body.name,
price: req.body.price
})
console.log("Log "+post.name );
post.save(function (err, post) {
if (err) { return next(err) }
res.json(201, post)
})
})
app.listen(3000, function () {
console.log('Server listening on', 3000)
})
There are two issues with your request in Postman (you removed the screenshot which showed these issues):
it's not formatted as proper JSON, but as a Javascript object
you're sending it as text/plain, not application/json
This is how I send request to Postman
{ name:"wewe", price:43}
One of two things is happening:
Either you aren't setting a Content-Type header in the request so the JSON parsing middleware you set up isn't being triggered or
You have, but since your JSON is invalid, it is failing to parse it.
You have to write valid JSON!
You can test your JSON with JSON Lint.
In particular, property names in JSON must be strings and cannot be identifiers. Strings in JSON must be delimited with " characters.
Your screenshot is not visible/trouble opening the screenshot. You need to be more specific with your question.
I think mongoose.connect("mongodb://localhost/tutorialkart"); here you need to specify the PORT localhost:27017
Make sure you defined the names "name" and "price" in your HTML/EJS and setting their value as the data you are trying to insert into database.
Use new before mongoose.model, mongoose.Schema
app.use(bodyParser.json()) should be app.use(bodyParser.urlencoded({ extended: true }));
I try to use Postman for generating some post transaction of my web but when I check the post method of my code it print the empty {} and add the empty {} to my list. I try to use middleware but the problem is still occurring.
This is my code.
// my code at restaurant.js
const express = require("express");
const router = express.Router();
const restaurants = require("../data")
router.get("/",(req,res) =>{
res.json(restaurants);
}
)
router.get("/:id",(req,res) =>{
const restaurantid = Number.parseInt(req.params.id,10);
const restaurant = restaurants.find((restaurant) => restaurant.id === restaurantid);
res.json(restaurant);
})
router.post("/",(req,res)=>{
console.log(req.body);
new_restaurant = req.body;
restaurants.push(new_restaurant);
res.json(new_restaurant);
}
)
module.exports = router;
//my code at index.js
const express = require("express");
const app = express();
const router = express.Router();
const restaurantsRouter = require("./routes/restaurants.js");
// Middleware
app.use(express.json());
app.use(express.urlencoded({extended:false}));
// Routes
app.use("/apis/restaurants",restaurantsRouter);
app.get("/",(req,res)=>{
res.send("<h1>Hello Express</h1>");
});
app.listen(3000,()=> {
console.log("Listening to port 3000");
})
module.exports = router;
The general reasons for an empty req.body on an incoming POST request are as follows:
You are failing to send the body properly with whatever client is sending the request.
You are failing to set the right content-type with the request that matches the type of the body data you are sending. If you're sending JSON, then you will need to make sure the incoming request has the content-type application/json.
You don't have the right middleware installed or working properly that will match the incoming content-type, read the body from the incoming stream, parse it and put the parsed results in req.body.
The middleware for parsing that content-type is not registered before your route handler in Express.
Some other middleware is "eating" the body before your middleware so the body is empty when it gets to your JSON middleware.
So, you will need to go through your POST request and eliminate each of these possibilities until you find the problem.
I have a localhost 1337 server and a 3000 server
1337 The server is sending data.
3000 The server is the receiving place.
1337 Send the data from the server
I want to get it from the 3000 server
It's the 1337 source first.
router.get('/send', function (req, res, next) {
var params = req.query; //post일때 사용
console.log(params);
// res.status(200).send({input:params});
request('http://localhost:3000/', function (error, response, body) {
console.log("#########################");
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', params);
});
});
Here we go to the 3000 server.
My data is also recorded in the LOG
But I do not think I'm going to log in, connect to the 3000 server, and send the data.
And 3000 server source.
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
var params = req.query;
console.log("333333333333333333333333333333333333333333");
console.log(params);
});
TITLE on the 3000 server and 33333333333 on the CONSOLE.LOG
I want to receive data from 1337!
Let me know the right way.
I'm also a beginner in Node, so this might not be the correct/most efficient way to do this. However, I've managed to connect a local webapp to a local Node server and pass data using Express, like so:
// server.js
var express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(cors());
var port = process.env.PORT || 3000;
http.createServer(app).listen(port, function (err) {
con.connect(function() {
console.log("Listening in port " + port);
});
});
This sets the server up for listening to requests, and now you can do something to specific requests, like:
app.post('/users', function(req,res) {
//Do something when receiving a POST request in "https://localhost:3000/users", like...
console.log(req.body); //... print the request content
});
Then all you have to do is send a request via GET/POST on your local server, and it should work.
Here is Express documentation, explaining some of the stuff it can do:
http://expressjs.com/en/api.html
Hope this helps!
This is my code:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
console.log(req.body)
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
I set a console in post method function but it displayed:
{}
User name = undefined, password is undefined
I couldn't get any data from response. I had lookup doc but I couldn't find any error. I don't still understand. What mistake did i make?
You should send your data using Postman with the content-type:application/json in the header. This will ensure that the server receives the data in JSON format.
I know what happens!
If I want to send data in form-data, here has good solution helps me:
Result is undefined when I use form-data in Postman
If I use x-www-form-urlencoded to send data, it's actually valid!
I find when postman send json data without content-type:application/json in headers, it's definitely error. Now, I have added it. It can be valid.
Thanks, everyone!