Im new with NodeJS and Im trying to send data to server with Angular
$scope.logearse = function () {
$http({
method: "POST",
url: "http://localhost:8888/login",
data: $scope.usuario
}).then(function successCallback(response){
console.log(response)
}, function errorCallback(error){
alert("No se han podido enviar los datos")
})
}
But in the server when I try to receipt the request is always {}
http.createServer(function(peticion, respuesta){
console.log(peticion.url)
console.log(peticion)
// We begin with "login"
if (peticion.url == "/login") {
console.log("Inside of Login)
var datosUsuarioLogin = '';
peticion.addListener("data", function(chunk) {
datosUsuarioLogin += chunk;
// function called when a new chunk of data is recibed
});
peticion.addListener("end", function() {
// When the data is recibed is transformed in JSON
var datosUsuarioLoginObjeto = querystring.parse(datosUsuarioLogin);
recuperarDatos(datosUsuarioLoginObjeto, respuesta);
console.log(datosUsuarioLoginObjeto) //return {}
});
//End of LOGIN "if"
}
}).listen(8888)
The thing is the same code works if I use a form with a regular submit but no if I try to use the $http of ANGULAR.
I try to use "params" instead of "data" but "params" transform the data in the URL and the code dont works.
You need to use bodyParser to parse the request body and place the result in request.body of route.
app.use(express.bodyParser());
And the request:
$http({
method: "POST",
url: "http://localhost:8888/login",
contentType: "application/json",
data: $scope.usuario // if usuario is not a valid json, you could to use JSON.stringify($scope.usuario);
Ok, after a lot of time trying finnaly I use Express but the version of Express I use dont allow simply bodyParser I need to install the body parser middleware
Link to body-parser
And the code
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.post('/', jsonParser, function (request, response) {
response.send(request.body)
});
Related
I am trying to send data through axios request to my backend script, but the body looks empty.
Here's a request sent from front-end:
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
}).then((res)=>{
console.log("api call sucessfull",res);
}).catch((err)=>{
console.log("api call unsucessfull",err);
this.props.toggleLoading(false);
})
Here's a back-end:
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);
})
But I am getting {} empty body. I am getting headers and other data but not data.
GET requests should not have a body.
Change the method from 'GET' to 'POST'
Like so:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
and change your api to expect a post
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
or
Change the data property to params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
and change the api to log out the params
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
and like #MaieonBrix said, make sure that your headers contain the content type that you are sending.
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 */
If you get an error that "bodyParser is deprecated", try this -
app.use(express.json()); //To parse JSON bodies (Applicable for Express 4.16+)
And use "post" method, if you want to get data from body of the HTTP request.
Try this
this.axios('realties', { params: this.filter })
I have a cordova project where I do the following request.
$("#asd").on("click",function(){
var data = {};
data.title = "title";
data.message = "message";
$.ajax('127.0.0.1:3000/register',
{
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function() { console.log('success');},
error : function() { console.log('error');}
});
});
Server side code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/register', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(3000);
But I get Internal Server Error 500 when I send the request. If I make a request simply by an html form or curl it just works fine.
What might be the cause of this?
$.ajax({
url:'/register', //or 'localhost:3000/register'
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function() { console.log('success');},
error : function() { console.log('error');}
});
Also you are required to use cors()
var cors = require('cors')
var app = express();
app.use(cors());
Also: https://enable-cors.org/server_expressjs.html
If it's related to the CORS, then you need to allow CORS on the server wich serves static via adding the following HTTP header:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Here is the example for Express (they put a wildcard * instead of http://127.0.0.1:3000).
Try JSON.stringify() in response
res.send(JSON.stringify(req.body));
This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 5 years ago.
server.js:
var express = require('express');
var app = express();
loggedIn = {};
app.use('/',express.static('www')); // static files
app.listen(8080, function () {
console.log('Port 8080!');
});
app.get('/user', function(req, res) {
if (typeof req.param('user') != 'undefined') {
user = req.param('user');
res.status(200).send('Works');
}
});
app.post('/user', function(req, res) {
user = req.param('user');
if (typeof users[user] != 'undefined') {
return res.status(405).send('Access Forbidden');
} else {
loggedIn[user] = "";
res.status(201).send('New User');
}
}
});
client.js requests:
$.ajax({
method: "GET",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
$.ajax({
method: "POST",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
Even though the GET request works exactly as expected and passes the parameter here, for some reason, the post request doesn't. In firebug, I notice the POST request receives no parameters whatsoever (POST user) while GET request does (GET user?user=XYZ). I am really at a loss right now.
You have to tell your express app to parse the request body
app.use(express.bodyParser());
for express 4+
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
For reference goto https://expressjs.com/en/4x/api.html#req and look at the section titled req.body
Hi so I have a jquery post data that i'm sending:
$.ajax({
type: "POST",
url: app.config.backend_2 + '/notifications/usernames',
data: data,
contentType: 'application/javascript',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
and this is my express receiver:
exports.save_usernames_for_notifications = function (req, res, next) {
var start = function () {
console.log(req);
};
start();
};
What do I do to get the data from the ajax to log it in the save_username_for_notifications function?
You need a body parser middleware in your expressjs application to parse your JSON req object
https://www.npmjs.com/package/body-parser
To configure it, you need this code
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST
Then to get your data in your express application just do this
console.log(req.body.data)
Question: What object is the JSON parsed to?
I'm successfully sending a JSON string to the server, but I haven't been able to access the object.
Client script, sending the JSON:
var loginCredentials= {
"username":creds.username,
"password":creds.password };
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
dataType: "json"
});
Login listener, waiting for and supposedly parsing the JSON:
function listen(){
app.use(express.bodyParser());
app.post('/login', function(req, res) {
var util = require('util');
console.log(util.inspect(req.body, false, null));
console.log(req.body.username);
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
Which logs:
Server running at http://127.0.0.1:8080/
{ '{"username":"username1","password":"badpassword"}': '' }
undefined
So it looks like my JSON is parsed right, but I'm trying to access it via req.body.username and it isn't stored there.
The bodyParser doesn't know that you're sending JSON. It assumes the body to be standard www-form-urlencoded, and therefore parses all of it as a single key.
Instead, send the proper content-type with your request:
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType : 'application/json',
dataType: "json" // response type
});
However, as mentioned in Do Not Use bodyParser with Express.js, you might just use the express.json() middleware only.