I sent a POST in my function to my server side (NodeJS), with the variable 'name'. 'name' is a string. However, I am unable to use this variable that I sent in the server-side.
I tried using req, req.body and req.body.name to access the variable I sent through POST. req gave me IncomingMessage {..}, req.body gave me {}, and req.body.name gave me undefined.
------Client Side------
var request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/addvoted", true);
request.send(name);
------Server Side------
app.post('/addvoted', function (req, res) {
var postBody = req.body;
console.log(postBody);
}
I expect the value of the variable name, which is a string, to be accessed in my server-side program.
I think this function send parameters via url,
try this code
req.query.name
replace name with variable name that you are sending
use npm body-parser
// create application/x-www-form-urlencoded parser
var bodyParser = require('body-parser')
var app = express()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
}``
Thank you.
Related
I posted data on angular front end as formData like this.
postButton(name: string): Observable<any> {
const formData = new FormData();
formData.append('name', name);
return this.http.post(environment.apiUrl + '/url, formData);
}
And I receive data on Node.js front end like this.
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/url', (req, res, next) => {
console.log(req.body)
res.status(200).json({
'message': 'OK',
});
});
But I get {},empty value.
what is wrong in my code?
Regards.
According to my knowledge, if you are sending some file then using FormData is useful. In other scenario's like this in which you are just sending plain text. You can just send a normal json object and it will work. You can try this.
postButton(name: string): Observable<any> {
return this.http.post(environment.apiUrl + '/url, { name });
}
In case you really want to use FormData then you need to install a npm package as:
npm install multer
And change your app.js to:
var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(upload.array());
app.use(express.static('public'));
app.post('/api/url', function (req, res) {
console.log(req.body);
});
module.exports = app;
Now, what multer does is, it supports multi-part form submission. And FromData uses that. To get the data from request body you need to install and configure multer.
Hope this works for you.
Delete the Content-Type header:
postButton(name: string): Observable<any> {
const formData = new FormData();
formData.append('name', name);
const httpOptions = {
headers: new HttpHeaders().delete('Content-Type')
};
return this.http.post(environment.apiUrl + '/url, formData, httpOptions);
}
When the XHR API send method sends a FormData Object, it automatically sets the content type header with the appropriate boundary. When the Angular http service overrides the default content type, the server will get a content type header without the proper boundary.
I want to send a images folder along with the other data. (name and openingHours);
this is my vuejs code that I use to submit data to the backend
const formData = new FormData();
formData.append("name", this.name);
formData.append("openingHours", this.openingHours);
formData.append("photos", this.selectedFile);
await this.$http.post("spa", formData);
Here my controller code
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
router.post('/', upload.array('photos', 10), async (req, res) => {
console.log(req.file);
console.log(req.body);
});
Here the req.file is undefined and photos also come under the body and also this openingHours is not an array. I pass and array in the front-end.
This is my body parser settings in the app.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
Can anybody tell me what's wrong with my code?
I want to pass openingHours as an JS array.
UPDATED
this is what I get if I console log openingHours in that method.
You need to stringify your array calling JSON.stringify before saving to FormData:
formData.append("openingHours", JSON.stringify(this.openingHours));
And on the backend you need to parse it calling JSON.parse:
const openingHours = JSON.parse(req.body.openingHours)
I've searched and tried other results, but none seem to render any results.
I'm trying to post data to the backend using postman as a test. The response is sending the 'success' message, but req.body returns an empty array every time I try. I'm using a node backend, with express and I'm trying to use routes. I've had success before, but for some reason I can't get it this time and my old code doesn't seem to work for this one. If I just log req, rather than req.body, I can see that the body is empty, the params are empty, but the url includes the params. I can post it, but it's rather long and I don't know if it's useful.
Here's the url I'm trying to hit: localhost:3000/?testParam=test&test=boop
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogTest', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
const postsRoute = require('./routes/post');
app.use(postsRoute);
module.exports = app;
post.js
const express = require('express');
const router = express.Router();
const postModel = require('../models/post'); //not using this yet
router.get("/", function(req, res){
console.log("Getting Posts...");
postModel.find({}, function(err, posts){
if(err){
res.send("{'status': 'error', 'response': "+err+"}");
}
else if(posts.length < 1){
res.send("{'status': 'null', 'response': {}}");
}
else{
res.send("{'status': 'success', 'response': "+posts+"}");
}
});
});
router.post("/", function(req, res){
console.log(req.body);
res.send('success');
});
module.exports = router;
I'm expecting the console to log {'testParam': 'test','test':'boop'}
also, I've tried parsing req.body as json and stringifying it, but it causes the server to crash.
I think you are confused about http methods and how they work.
req.body is the POST request body, it is the data passed by the client when he sends a POST request to your api endpoint. If you are not sending any data in your POST request, then req.body will be empty.
In your example, to get the data from a request like localhost:3000/?testParam=test&test=boop you would need to look in req.params instead of req.body.
You need to try accessing the params variable of the request by code, trying to go through a log to find params might not be accurate therefore try
router.post("/", function(req, res){
console.log(req.params);
res.send('success');
});
I am building an API with Node.js, Express.js, and MongoDB. When I submit the form and use the req object in the route, the req.body object is empty.
req.body returns {} when I call the get_user function through the browser using postman at https://localhost:3000/users/0.
app.js:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
bodyParser = require('body-parser');
var mongo_server = require('./server')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var routes = require('./routes/users')
routes(app);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'});
});
app.listen(port);
mongo_server.mongo_connection
module.exports = app;
userController.js:
var mongoose = require('mongoose'),
user = mongoose.model('users');
exports.get_user = function(req, res) {
console.log(req.body.id);
user.findById(req.body.id, function(err, user) {
console.log(req.body);
if(err)
res.send(err);
res.json(user);
});
};
userRoutes.js:
module.exports = function(app) {
var users = require('../controllers/userController');
app.route('/users/:userid')
.get(users.get_user);
}
I think you're confusing request parameters and request bodies. A request body is when you send information with the request like a payload, such as in a POST request when you send JSON to the server to, for example, create a new user:
{
"username": "jd123",
"email": "jd#example.com",
"name": "John Doe"
}
But in your case, you're looking for parameters, things passed through the URL like you've set up:
/users/:userid
That allows you to navigate to with a GET request:
/users/0
And then you can get the 0 as a string from req.params.userid not req.body.id. Request parameters and bodies are different. Parameters are for navigating to a varying route such as a user profile page, where the URL varies and reflects which route you want to go to by a user's ID.
Bodies are used for the payload of a request such as POSTing, PATCHing, and PUTing, giving information on what to update or create on the server.
I am trying to post data from my react. Backend - express.
Here is backend code:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");
mongoose.connect("mongodb://localhost/blog-react");
//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}
app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});
React code:
var requestUrl = "/api/blogs";
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});
When I post data via axios - request.body is always {}
But if I post data via regular form - all is correct - request.body contains all expected data.
What am I doing wrong with axios?
You are missing one middleware, bodyParser.json(). Add it to your configuration.
mongoose.connect("mongodb://localhost/blog-react");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));
For people using Express>=4.16, bodyParser has been changed to the following:
app.use(express.json());
For me the issue was valid JSON format including double quotes on the variables.
This did not work
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
This DID work (with double quotes around email and password)
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */