here is my client ajax code:
var sendData = JSON.stringify({
name: document.forms["token"].name.value,
password:document.forms["token"].password.value
});
$.ajax({
url:'http://localhost:8088/log/',
type:'POST',
contentType:'application/json',
data: sendData,
dataType:"json"
})
and here is my node server code:
const http = require('http');
const express = require("express");
const jwt = require('jwt-simple');
const moment = require('moment');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
var expires = moment().add(7,'days').valueOf();
var token;
app.set("jwtTokenSecret","luo");
app.use(bodyParser.urlencoded({ extended: false }));
app.all("/log",function(req,res){
var name = req.body.name;
var password = req.body.password;
console.log(name,password)
...
}
I found that the name and password are both undefined in node server, the json data on client is correct. I have tried a lot to solve it , but I can't, I need your help, thanks.
$.ajax already serialize data, so, is not necessary to use JSON.stringify if you already set dataType to 'json'.
Try to send data as plain object.
In my case i make ajax call something like this.
From client side make the ajax call:
function _sendData(){
var host= 'localhost'; //or you can set your host by your choice.
$.post(host+'/post',$('#horizontalForm').serialize(),function(response){
// respose
});
}
From node.js server side code given below,
var qs = require('querystring');
app.post('/post',function(req,res){
if(req.method=='POST'){
var body='';
req.on('data',function(data){
body+=data;
console.log("before proccess = "+body);
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
request.connection.destroy();
}
})
req.on('end',function(){
var post = qs.parse(body);
console.log(post.user);
console.log(post.message);
})
}
})
and the HTML part be like,
<form method="POST" action="/post" id="horizontalForm">
<p class="lead">
<input type="text" name="user" value="testUser" id="userId"/>
<div>
<input type="text" name="message" id="messageId"/>
<input type="button" value="Send" class="btn btn-lg btn-default" id="getData" onclick="_sendData();"/>
</div>
</p>
</form>
N.B : To install query string you can run the command npm install querystring --save
Don't forgot to include jquery.js and ajax lib in your html.
Check document.forms["token"] contains name and password by using console.log('values',document.forms["token"]) expression .
If values are there ,
Then call the api,
var sendData = {
name: document.forms["token"].name.value,
password: document.forms["token"].password.value
};
var saveData = $.ajax({
url: 'http://localhost:8088/log/',
type: 'POST',
contentType: 'application/json',
data: sendData,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
Related
This question might have been ansked before, but i can't seem to find the correct answer for it. I'm working on a Ionic project where i've created another project with Node.js and express.js to handle all my http requests. Both are running on localhost at the moment. When i'm trying to send some data from my client-side to to server-side, the data that i'm getting from the request looks like this when i console.log(req.body):
{ '{"username":"hello#hello.com"}': '' }
I tryed both req.body[username] and so on to get the data, but then it just gets undefined.
My controller for handling the http request looks like this:
$scope.submit = function(){
var username = $scope.username;
console.log($scope.data.username);
$http({
method: 'POST',
url: 'http://localhost:8000/api/users',
data: username,
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});
Html element
<input type="text" ng-model="data.username" name="name">
Server-side API looks like this:
router.post('/users', function (req, res) {
var username = req.body;
var newUser = new User({
username: username
})
newUser.save(function (err) {
if (err) {
return res.send(500, err);
}
return res.json(200, newUser);
});
});
Server.js bodyparser included
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
Object have keys and values
{ key: value }
The object on the body is beeing sent in some wrong way since you're sending a object with they key '{"username":"hello#hello.com"}' which has the value ''.
I would recomend fixing how you're posting to your nodejs/express server. But you can get the value by some hacks. Like this.
const body = {'{"username":"hello#hello.com"}': '' }
const keys = Object.keys(body);
const parsed = JSON.parse(keys[0]);
console.log(parsed.username);
https://jsfiddle.net/wejh0fsk/2/
Edit: So what I am doing here is getting all the keys of the object. There's only one key '{"username":"hello#hello.com"}'. Since that key is a string I am parsing it to get a object. Now I have a object
{ username: 'hello#hello.com' }
And finally I'm logging out the username.
The right solution would to fix how your sending your data to the express server.
I don't quite understand your controller. Your ng-model is data.username but then you're putting
var username = $scope.username
Which should be
var username = $scope.data.username // (that's at least what you're binding to in your view)
Also you want to send an object with the post, not just the value
$scope.submit = function(){
var username = $scope.username;
console.log($scope.data.username);
$http({
method: 'POST',
url: 'http://localhost:8000/api/users',
data: { username: username },
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});
I am not sure on express parsers but I don't know why you're calling the bodyparser twice. The first one should be enough.
I am trying to send form data via ajax to a nodejs server. Previously asked on this post.
Here's what my code looks like:
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter a value between -90 and 90 for lat, and -180 and 180 before hitting
submit.</p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" value="15" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" value="25" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" value="-10" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" value="120" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
console.log("hi hi");
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
// console.log(val);
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log("hi helo");
}
});
});
});
</script>
</div>
My server side code looks like this :
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log("hey");
console.log(req.body);
res.send("hi back!");
});
I am trying this out but I am unable to send the form successfully, and upon hitting submit, I get "hey" and an empty {} as logged output. I am not able to log the formData on the client side, regardless.
Can someone point out what I might be doing wrong?
You didn't assign a form to formData() that's why you're not sending any data to the server.
var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);
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);
});
})
How do I parse my JSON with external middleware now that Express doesn't carry a body parser?
For a while, I was using Express bodyParser to receive and respond to JSON posts to the server. Each time I started up the server, express said something about bodyParser being removed soon, and sure enough, I've updated and now JSON requests seem to be showing null.
So I didn't understand how middleware worked, and had followed an express tutorial to use the body parser. Now, using separate body parser middleware, it seems I'm doing it wrong.
Before, my syntax was:
app.use(express.bodyParser());
Now, with the module body-parser as middleware, it's like this:
app.use(bodyParser.json());
And an example as a whole:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
function listen() {
app.use(bodyParser.json());
app.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
console.log('User ' + username + ' is attempting login...');
validate(username, password, function (err, result) {
if (err) loginFail(req, res, err);
else loginSucceed(req, res, result);
});
});
app.listen(3333);
}
listen();
I tried express.json() as the middleware, but that triggers the fatal error:
Error: Most middleware (like json) is no longer bundled with Express
and must be installed separately. Please see
https://github.com/senchalabs/connect#middleware.
That link leads to the body-parser middleware that I'm using via app.use(bodyParser.json()).
Update:
Using bodyParser.json() results in no error, but the data values are null:
User undefined is attempting login...
My client code should be fine, but here it is for completeness:
function sendLogin() {
popLogCreds(creds);
var loginCredentials = {
"username": creds.username,
"password": creds.password
};
console.log("Sending login credentials: " +
JSON.stringify(loginCredentials, null, 4));
request = $.ajax({
url: "http://54.186.131.77:3333/login",
type: "POST",
crossDomain: true,
data: loginCredentials,
dataType: "json",
error: function () {
postError("Uh Oh! The Officeball server is down.");
},
success: function (data) {
var ParsedData = data;
sessionStorage.username = creds.username;
sessionStorage.password = creds.password;
sessionStorage.fname = ParsedData.fname;
sessionStorage.lname = ParsedData.lname;
sessionStorage.rank = ParsedData.rank;
console.log(sessionStorage);
window.location.replace("app.html");
}
});
}
Which results in:
Sending login credentials: {
"username": "jonathan#evisiion.com",
"password": "J******!"
}
And then the result is the POST's error output, which is, as above:
error : function () {
postError("Uh Oh! The Officeball server is down.");
}
Don't take that error message literally. Just means an error happened. The server is, in fact, getting that request, as shown up above.
By default, $.ajax() sends data URL-encoded as mentioned in the description of the processData option:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
The body-parser that corresponds to that Content-Type and format is urlencoded():
app.use(bodyParser.urlencoded());
If you'd rather use JSON for the request, you'll need to provide the data already formatted as such along with a matching contentType that bodyParser.json() recognizes:
request = $.ajax({
url: "http://54.186.131.77:3333/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType: 'application/json',
dataType: 'json'
// ...
});
Note for cross-domain: With these modifications, the server will have to handle preflight OPTIONS requests for the route.
And, note that a bodyParser isn't needed for HEAD or GET requests as the data is included in the URL rather than the body. Express parses that separately into req.query.
In your node code,
make sure you put these two lines of code
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
......then your other code follows..
enjoy...