My client side
$.post("http://localhost:3000/scrape",
{
data: 'something'
},
function(data, status){
console.log(data);
});
What I do in node.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/scrape', function (req, res) {
console.log(req.body.data)
});
But I got undefined in console.log(req.body.data), any idea why?
Your data must be of json format. since you are using bodyParser.json().
Try setting the http header, Content-type as application/json in your $.post call and send a valid json structure as data
$.ajax({
url: "scrape",
type: "POST",
data: JSON.stringify({ someData : "someData}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(data)
},
error: function(){
console.log('error in sending request')
}
})
console.log(req.body.data)
returns undefined because the data is in req.body you should console.log(req.body)
and add app.use(bodyParser.urlencoded({extended: false})); so that data not in json format can also be parsed.
if you want req.body.data have data then make request like
$.post("http://localhost:3000/scrape",
{
data: {data: 'something'}
},
function(data, status){
console.log(data);
});
also your request is not sending any response you need to do something like
app.post('/scrape', function (req, res) {
console.log(req.body.data)
res.status(200).json({data: reqr.body.data});
});
hope it helps :)
Related
Please help me with the below POST request that I'm trying to make. Below is the code snippet.
const express = require("express");
const bodyParser = require("body-parser");
//const request = require("request");
const https = require("https");
const request = require('request-promise');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/test.html");
});
const data = {
"some_header":{
"name":"xxxxx"
}
};
const jsonData = JSON.stringify(data);
console.log(jsonData);
app.post("/post", function(req, res){
const url = "xxxxxxxxxxxx";
const options = {
method: "POST",
body: data,
json: true,
headers: {
ContentType: "application/json",
Authorization: "nhgjgjhgjghjghj"
}
}
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
// res.send("success");
console.log("success");
} else {
//res.send("Failed");
console.log("failure");
}
response.on("data", function(data) {
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
});
app.listen(process.env.PORT || 3000, function() {
console.log("The app is up and running on Port 3000");
});
I'm getting 200OK response from the external server, but unable to post the data. When I logged the response data from the server, I received this success
{ require_login: true }
"Success" is the console log message. require_login: true is the response I'm getting from the server. where am I going wrong?
Try to add Basic before you api key. Also, if you are using base64, then check that original string is right one and should be something like: login:password
headers: {
ContentType: "application/json",
Authorization: "Basic BAsE64Format or api:key or login:password"
}
headers: { "Content-type": "application/json", Authorization: 'Basic ' + Buffer.from('CtB2HZwaRdGggr1g4K').toString('base64') }
enclosing the content-type with quotes and converting the API key to base 64 did the trick
I am using the ajax to post the data from javascript front end to express js has backend server. How i can get the posted data, in express js api method req params. I am facing issue when i try to parse the request data below is my code.Please help me to solve this
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: { name: 'Justin', number: '662***' },
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
alert("error");
}
});
Express Js server side
const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
//deploy the smart contract
app.post('/api/save_user', (req, res) => {
console.log((JSON.parse(req.body)));
res.send({})
})
Error Log
SyntaxError: Unexpected token n in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/node_modules/body-parser/lib/types/json.js:158:10)
at parse (/node_modules/body-parser/lib/types/json.js:83:15)
at /node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/raw-body/index.js:224:16)
The problem is that jquery expect you to pass an string with the json inside. try like this:
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: JSON.stringify({ name: 'Justin', number: '662***' }),
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
}
});
when pressing a button this code gets executed
function submitData() {
$.ajax({
type: 'GET',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: JSON.stringify({ // some test data
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
})
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this
app.get('/questionnaire/submit', function (req, res) {
var data = req.query; // Get the data object from the Ajax call
console.log(data);
res.send(null); // Send nothing back
});
Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.
Even when writing res.send("Success"); the client will log "Error". What am I missing?
Update:
I installed the body parser middleware and use this code now
my app.js
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const handlebars = exphbs.create({
defaultLayout: 'index',
extname: 'hbs'
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'Public')));
app.listen(8888, function () {
console.log('Server running on port 8888');
});
my route
module.exports = function (app) {
app.get('/questionnaire', function (req, res) {
res.render('questionnaire');
});
app.post('/questionnaire/submit', function (req, res) {
var data = req.body;
console.log(data);
res.send(null);
});
};
and my client function
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
dataType: "json",
data: JSON.stringify({
satisfactory: $("#edtSatisfactory").val(),
improvement: $("#edtImprovement").val(),
rating: currentRating / ratingElements.length
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
And when executing the Ajax call the client still runs into .fail()
Client request is :
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: {
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
}
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this Using bodyParser middleware in your node backend
:
app.post('/questionnaire/submit', function (req, res) {
var data = req.body; // Get the data object from the Ajax call
console.log(data);
res.end(); // Send nothing back
});
You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.
url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext
If you're using POST don't forget:
'Content-Type': 'application/json',
Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:
npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
This will parse your JSON and add it to req.body.
Try this..
Client Side
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
'Content-Type': 'application/json',
data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
}).done(function () {
console.log('hi')
}).fail(function () {
console.log("Error");
});
}
On server Side:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/questionnaire/submit', function (req, res) {
var data = req.body
console.log(data);
res.send(null); // Send nothing back
});
You have to install body-parser library using following command.
npm install --save body-parser
It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question.
If you are not understanding anything plz comment below.
You just have to replace
dataType: "json",
with this:
'Content-Type': 'application/json'
in $.ajax request
Hope this will work.. I have tried & tested.
I defined a JSON, and post it to back end (Node.js).
var imj = {};
imj.images = [];
$.post("/image/uploadImages", imj, function(feedback){
.....
However, what the backend received was
{}
the "images" entry disappeared.
Here's the backend code:
exports.uploadImages = function(req, res) {
if (typeof req.body.images == 'undefined') {
return res.json({
code: 1,
message: "parameter incomplete"
})
}
.....
So the backend return the error {code:1, message:'parameter incomplete'}
Anyone knows why? If I want the backend to receive this empty array, what should I do?
What's the contentType nodeJS is expecting on the back-end? The default contentType for the $.post method is application/x-www-form-urlencoded. If you're endpoint is looking for application/json, you'll always see an empty input.
$.post sends url encoded data, so you need to use $.ajax and specify the content type as well as JSON stringify the data.
var data = {};
data.images = [];
$.ajax({
url: '/image/uploadImages',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data)
}).done(function(data) {
console.log(data); // { images: [] }
});
On the server side make sure to use a body parser.
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', function (req, res, next) {
console.log(req.body); // { images: [] }
res.json(req.body);
});
app.listen(9000);
I'm running a server in nodejs with express to serve an html form within the file index.html to a client like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
res.json(req.body);
});
app.listen(8080);
req.body gives me the form input. Now I need to send back req.body to the client, and to do this I'm using ajax on the client side (inside index.html) like this:
var data;
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: data,
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})
However when I click the button submit I get Object {} in the browser console and not the form input.
What am I missing here?
There are two issues in your code:
First, as the comments mention, bodyParser() is deprecated, you should be using the specific bodyParser middlewares (json, text, urlencoded, raw). So in your case:
app.use(bodyParser.json())
Second, your client side call to jQuery.ajax should stringify your data. Like this:
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: JSON.stringify(data),
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})