javascript..when i do POST method ..it shows an space appending - javascript

coding image
output image
it showing a extra space when i do post method using REST API method

You are not parsing your data correctly. You need to POST the object as JSON.stringify(yourobject) and then have nodejs run jsonencoder to parse the data correctly, otherwise your request body will always be null. Below is an example.
var jsonencodedParser = bodyParser.json({ extended: false });
app.post('/test', jsonencodedParser, function (req, res) {
console.log('this is req.body');
console.log(req.body);
res.status(205)
res.send();
})//end function

Related

Request post return an empty object in NODE.JS

I don't know why but i try to send an object in my back. I can find good information in my network's payload but my req.body return everytime an empty object
my probleme
add app.use(express.json());
express.json() is a middleware that allows express to recognise the json data in request object.
Also your controller is not sending any response back, for that use:
app.post("/", (req, res) => {
res.status(200).json({"data" : req.body});
}

How to read/parse Array in form-data node js

Please check the above image, I am trying to read this in Node Js. I am using express js and have tried debugging req.body. It is returning an empty object {}.
I am using app.use(bodyParser.json({ extended: true })); . To read body but unable to read the data.
I can parse/read json object which are sent in raw(json) format
Edit:
Added multer
But Still Return empty object {}
router.post('/array', uploads.none(), (req, res, next) => {
console.log(req.body)
})
bodyParser.json is used to parse application/json content type. The solution is to use multer middleware to parse form-data content type.
https://www.npmjs.com/package/multer

How to send API response through body with node.js?

So I have an API that works fine and responds as I need, but I was wondering how I would set the response from the API to be in the body?
Right now it's just setting the response to be in a <pre> tag on the actual website (if I inspect element it shows like below):
<body><pre>{api response}</pre></body
but the only way I can access it is if it's in the body response.
If I check the console.log one the response, it just shows a bunch of blank spaces, so I was wondering how I would set up the API so it will respond in the body? Any help would be appreciated.
For the API I'm using Node.js with express and request packages if that helps at all
I'm not sure if i understand your question, but i'm sure that you can insert your response in any place you want. Try using jade or mustache (handlebars).
Here is the example from the Express website:
app.get('/', function (req, res) {
res.send('Hello World!')
})
This sends "Hello World!" in the HTTP response body.
So to send the API result instead you need to:
Set the appropriate content-type header
Send the result of getting stuff from the API
Such:
app.get('/', function (req, res) {
var api_response = get_data_from_api();
res.set('Content-Type', 'application/xml'); // or application/json or whatever
res.send(api_response);
})

AJAX and Node JS/Express post not sending or receiving data

I am new to Node and I am trying to use app.post, everything works fine including the console log whenever the action is executed but it does not receive the data sent by the AJAX from main.js.
Here is a snipper of main.js which sends it:
$.ajax({
type: 'POST',
data: '{"title":'+ this.messageInput.value +'}',
url: 'http://localhost:3000/send'
});
Here is my config.js which should be receiving the data:
app.post('/send', function(req, res) {
console.log(req.body);
console.log('Send button clicked');
});
I am using bodyParser with express. So that is why I am using req.body. When I console log req.body I get undefined. When I console log req, I get a list of data but not what I sent.
I hope someone can help!
It's good that you are using body-parser, but have you defined a JSON parser in your app?
You didn't paste all of your code so add this if you don't already have it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
console.log(req.body);
console.log('Send button clicked');
})
Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)
var myData = {};
myData.title = this.MessageInput.value;
Then in your Ajax code, just use myData:
$.ajax({
type: 'POST',
data: myData,
url: 'http://localhost:3000/send'
});
Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out

Error when doing post with express JS

I am testing the post method to create a todo item as follows. I am using postman in chrome to simulate the post method call. However, it does not work and gives me the below error. I suspect something is wrong with the way body-parser library is working. What am I doing wrong here?
1 SyntaxError: Unexpected token b
2: at parse (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/types/json.js:83:15)
3: at /Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/read.js:116:18
4: at invokeCallback (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:262:16)
5: at done (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:251:7)
6: at IncomingMessage.onEnd (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:308:7)
7 at IncomingMessage.emit (events.js:104:17)
8 at _stream_readable.js:908:16
Code:
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
//MIDDLEWARE
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
// TODOS
var todos = [
{ body: "take out the trash",completed: false},
{ body: "Do the laundry",completed:true},
{ body: "Make a screencast",completed:false}
]
app.post('/todos', function (req, res){
console.log("todo:", req.body);
var todo = req.body;
console.log("todo:"+todo);
todos.push(todo);
res.status(200).json(todo);
res.send('OK')
})
Further I observe that the problem is because of this line.
app.use(bodyParser.json());
Are you sure you are sending the request as JSON? Make sure you've selected it in Postman - https://imgur.com/j0M7TEX.
If that didn't work, you can try the following -
...
app.post('/todos', function (req, res){
console.log("todo:", req.body);
var todo = req.body;
console.log("todo:"+todo);
todos.push(todo);
// Only try to send a single response.
res.json(todo);
});
It looks like you were trying to send two responses, one containing JSON, and another with text/plain ('Ok').
http://expressjs.com/fr/api.html#res.json
It seems like your program is trying to interpret the post data as json data - and generating an error when it trys to parse the request data which is probably url-encoded.
Perhaps consider sending your data in json format. You will have to set the request headers to indicate the datatype is json. See this answer for an example:
Angular JS POST request not sending JSON data
I just created a new session in postman and it started working. I am not sure if there is a caching effect but it works now. I did not make any code change at all. Posting this as the solution now.
Just don't put quotes on your JSON value.
Not "okay2" but just okay2.
I think that postman adds the quotes himself if needed and in this case creates ""okay2"" which isn't valid JSON.
By the way you can test by clicking on the "row" radio button and write your own JSON.

Categories

Resources