https://codeforgeek.com/2014/07/angular-post-request-php/
Hi I was following the above link to give post request from angular js to node js. I received the data posted in below format when i give
console.log(req.body);
{ '{"email":"test#test.com","pass":"password"}': '' }
and when i try to get the value as below, it says undefined.
var email = req.body.email;
console.log(email);
I am unable to get the value of email and pass. Thank you
change the client side header code to headers: { 'Content-Type': 'application/json' }
Your Angular code is sending JSON data, but your Express app is parsing it as URL encoded data.
You probably have something like this in your Express app:
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded());
That last line should be:
app.use(bodyParser.json());
You did not well explain the problem , please next time try to post a bigger part of your code so we could understand what you wanted to do / to say .
To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):
1) receive a request send from angularJS or whatever inside your nodeJS app
//Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')
// we need these variables for the post request:
var Vorname ;
var Name ;
var e_mail ;
var Strasse ;
app.use(myParser.urlencoded({extended : true}));
// the post request is send from http://localhost:8080/yourpath
app.post("/yourpath", function(request, response ) {
// test the post request
if (!request.body) return res.sendStatus(400);
// fill the variables with the user data
Vorname =request.body.Vorname;
Name =request.body.Name;
e_mail =request.body.e_mail;
Strasse =request.body.Strasse;
response.status(200).send(request.body.title);
});
2) Do the inverse send a POST request from a nodeJS application to another application
function sendPostRequest()
{
// prepare the data that we are going to send to anymotion
var jsonData = querystring.stringify({
"Land": "Land",
"Vorname": "Vorname",
"Name": "Name",
"Strasse": Strasse,
});
var post_options = {
host: 'achref.gassoumi.de',
port: '443',
method: 'POST',
path: '/api/mAPI',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': jsonData.length
}
};
// request object
var post_req = https.request(post_options, function(res) {
var result = '';
res.on('data', function (chunk) {
result += chunk;
console.log(result);
});
res.on('end', function () {
// show the result in the console : the thrown result in response of our post request
console.log(result);
});
res.on('error', function (err) {
// show possible error while receiving the result of our post request
console.log(err);
})
});
post_req.on('error', function (err) {
// show error if the post request is not succeed
console.log(err);
});
// post the data
post_req.write(jsonData);
post_req.end();
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
}
So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.
For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation
I hope you enjoyed this and Viel spaß(have fun in german language).
Related
I'm working with an external API from Shipstation. I can do a GET request to pull the information in just fine into Nodejs, but I can't figure out how I can transfer that data client-side to manipulate within Angular? I've been struggling with this for a few days now and all my googling searching isn't helping out.
server.js
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static('public'));
var Orders = require('./controllers/ordersController');
app.use('/orders', Orders);
app.listen(3000, function() {
console.log('I am live on port 3000');
});
ordersController.js
var request = require('request');
module.export = request({
method: 'GET',
url: 'https://ssapi.shipstation.com/orders/listbytag?orderStatus=awaiting_shipment&tagId=32099&page=1&pageSize=100',
headers: {
'Authorization': 'xxxxxxxxxxx'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
});
I figured the best way was to put the GET request in its own "orders" module, export it, and then have angular access that route in an http request (/orders). Sounds good in theory, right?
I appreciate the help in advance! Thanks guys!
I'm assuming that the ShipStation API provides JSON which is easily consumable by Angular.
You can load the JSON into your Angular app like this:
$http.get('/orders:3000', function(data) {
$scope.Orders = data;
console.log($scope.Orders);
});
Add this to your controller, then check the browser's developer console to see the output. From there, you can manipulate the JSON object however you need and display the information in your HTML view.
I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.
var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
console.log("Test Output :");
res.status(200).send('Hello User');
});
app.listen(8080);
Below is my angular code
var myapp = angular.module('myapp',[]).controller('myappController', ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
.then(function(response)
{
window.alert("Success");
$scope.emdata=response.data;
},function(errorresponse)
{
window.alert("Error");
$scope.emdata=errorresponse.status;
});
}]);
I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.
When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?
Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).
Fix value in
$httpProvider.defaults.headers.common
or set needed one in
$httpProvider.defaults.headers.get = { ... };
or just use
var requestParams = {
method: 'GET',
url: '...',
headers: {
...
}
};
$http(requestParams).then(...);
Take a look at Setting HTTP Headers in official manual for more details.
I want to retrieve various request params in express sent to me by angular but I keep on getting 404 error:
Code angular controller:
var config = {
params: { userid: "userffvfid ",
pass:"abcd"
}};
$http.get('/erai',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response; });
Node js/Express js code:
app.get('/erai',function(req,res){
console.log("got request");
console.log(req.params.userid);
console.log(req.params.pass);
res.send("hello");
});
How do i access the params properly and respond to it properly w/o getting 404 error?
When making a get request like that any payload will be appended in the url.
So the final request url will be something like
http://www.example.com?user=John&password=Doe
To access those variables in express use the req.query object
in your case
var userid = req.query.userid
var pass = req.query.pass
If you go the POST way your data will be in the payload
You will have to use a body parser middleware and then access the data with
req.body
I am using Angular 1.3 and node.js 0.12.2 for a project. I am hitting the node.js api using
$http.post("url", request_data){}
And on server side using this:
console.log(req.body)
But everytime the api gets called, it gets empty object {} for request_data , Unable to get what the problem is. I have used body_parser like this:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
Have also tried adding content-type header in angular $http as:
headers : {'Content-Type': 'applicatio n/x-www-form-urlencoded'}
But not getting request data.
EDIT:
Node.js code :
router.post('/url',function(req,res){
console.log(req.body)
})
Note: Developer Tool's network tab showing the data, I am sending, in request header correctly, but node.js server not receiving in req.body.
In POSTman getting data is correctly in response.
some ideas :
Maybe an URL error ? Make sure you aren't using a prefix like app.use('/api', router);
Look at the Content-Type :
application/x-www-form-urlencoded --> 'var1="SomeValue"&var2='+SomeVariable
application/json;charset=UTF-8 --> {var1:"SomeValue", var2:SomeVariable}
You could use $http more explicitly :
$http({
url: '...',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'var1="SomeValue"&var2='+SomeVariable
});
My best guess is that your angular $http request URL is pointing to a bad end-point.
Angularjs
// data to post nodejs server
var _data = {
'message': 'Can I help you?'
};
// angularjs $http post request
$http.post('/api/url', _data).then(function(respond){
// if success
console.log(respond);
}, function(error){
// if an error
console.error(error);
});
Nodejs
// router function
function something(req, res) {
// console.log the request body
console.log(req.body);
// respond JSON object
var _respond = {
'status': 200
};
// expressjs respond a JSON with status code 200
res.status(200).json(_respond);
}
// register route URL
router.post('/api/url', something);
Note that the code end point URLs are same : /api/url
Therefore as your code sample in above question, you'r missing a /
I'm trying to pass multiple parameters in a URL with no luck. I'm not sure if it makes a difference but I am doing it through Angular. I'm trying to send the request to a REST API backend that I know works for single requests. Here is what my backend looks like
index.js
var express = require('express');
var router = express.Router();
var game = require('./game');
router.get('/api/v1/gameRefined/:from_datepicker:to_datepicker:from_timepicker:to_timepicker:selectLevel', game.getAllRefined);
module.exports = router;
game.js
...dbconnection stuff...
var game={
getAllRefined: function(req, res) {
var refines = req.params;
console.log("getting refined games");
pool.getConnection(function(err, connection){
var query = connection.query('SELECT * FROM game WHERE date >= ? AND date <= ? AND time >= ? AND time <= ? and level = ?', [refines.from_datepicker, refines.to_datepicker, refines.from_timepicker, refines.to_timepicker, refines.selectLevel], function(err, rows) {
connection.release();
if(err) {
throw err;
}else{
res.json(rows);
}
});
})
},
}
module.exports = game;
I send the request from this factory
.factory('gameFactory', ['$http',
function($http) {
var _gameFactory = {};
_gameFactory.getRefinedGames = function(dateFrom,dateTo,timeFrom,timeTo,level) {
var encodedParam = encodeURIComponent(baseUrl + '/api/v1/gameRefined/?from_datepicker='+dateFrom+'&to_datepicker='+dateTo+'&from_timepicker='+timeFrom+'&to_timepicker='+timeTo+'&selectLevel='+level+'');
return $http.get(encodedParam);
}
return _gameFactory;
}])
That sends this request that comes back as a 404:
http://localhost:8100/http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1%2FgameRefined%2F%3Ffrom_datepicker%3D2015-02-05%26to_datepicker%3D2015-02-19%26from_timepicker%3D12%3A00%26to_timepicker%3D18%3A00%26selectLevel%3D1
I have tried it encoded and not encoded, with forward slashs, with semi colons, but nothing has worked so far.
I don't know why a localhost gets appended at the start, but even trying it in postman without the first localhost still is a 404 error.
How should I be doing this? Any help is appreciated. Thank you.
First, other than separating the work into a factory, you aren't really using Angular here. Second, I would consider posting to your API, return JSON results from the API, and then use a promise to read the data back into Angular.
Use $http.post
Let Angular do this work for you. Something like the below will generate the URL request for you. The return value of $http is also a promise, so using .success and .error will allow you to parse any returned data as well, even if it is just a success or failure message - but it is a great method of passing data between server/API and client.
.factory('gameFactory', ['$http',
function($http) {
return {
reachAPI: function(dateFrom, dateTo) {
$http.post('http://localhost:8080/api/v1', {
'dateFrom': dateFrom,
'dateTo': dateTo
})
.success(function(data, status, headers, config) {
*things happen*
data.somethingReturned // from your API
});
}
}]);
Consider body-parser
I know you said you have confidence in your REST API structure, but body-parser is an Express middleware that can parse URL-encoded strings and may prove helpful in reading your data. Personally, I think it lends towards more readable code.
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
router.route('/api').post(function(req, res) {
*things happen*
req.body.dateFrom //find your data
*things happen*
res.json(returnedData);
});
Hope that helps