Can't access to POST parameters using expressJs with AngularJs POST Request - angularjs

I can't access to my post parameters when I'm doing post request with angular, here is my angular code :
var request = $http({
method: 'POST',
url: '/api/login',
data: {
login: 'alex',
password: 'test'
}
})
.success(function (res, status, headers) {
if (res.token != 'undefined'){
user.token = res.token;
user.login = credentials.login;
user.userid = res.userid;
user.islogged = true;
$cookieStore.put("user", user);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
Here is my back-end code in my router file :
/************ API ******************/
app.post('/api/login', user.login);
And here is the code of my user controller
exports.login = function(req, res) {
console.log(req);
var user = {
login: req.query.login,
password: sha1(req.query.password)
};
...
}
I have nothing in req.query object otherwise if I make my request with Advanced REST Client plugin for chrome everything work fine.
Note: I'm using body-parser module to read parameters of my request.
Here is the github repository : https://github.com/alex3165/numeractive/tree/dev/node

Make sure you enables the use of json parser
var bodyParser = require("body-parser");
app.use(bodyParser.json());
Note: you have to install body-parser package, just open your terminal (command prompt in windows), chnage your directory to the root of your project and type the following
$ npm install body-parser --save

Related

Angularjs Access-Control-Allow-Origin

I have Angularjs app connects to a server using API, and i'm using token authentication, when i use Postman to get the token, it works perfect, but when i'm use Angulajs with the same header and parameters i got error:400.
When i checked both requests using Fiddler, i found that the request from Angularjs is missing Access-Control-Allow-Origin: * header.
How to fix this?
Here is the service used to get the token:
AuthenticationApi.Login = function (loginData) {
//POST's Object
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
//the data will be sent the data as string not JSON object.
$http.post('http://localhost:53194/Token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(function (response) {
console.log(response);
localStorageService.set('authorizationData',
{
token: response.access_token,
userName: loginData.userName
});
Authentication.isAuth = true;
Authentication.userName = loginData.userName;
console.log(Authentication);
deferred.resolve(response);
},
function (err, status) {
logout();
deferred.reject(err);
});
return deferred.promise;
};
for the API server, i'v done CORS:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
i found the problem and i fixed it.
in the API server, i have this code:
var cors = new EnableCorsAttribute("*", "*", "*");
cors.PreflightMaxAge = 60;
config.EnableCors(cors);
The problem is in the PreflightMaxAge, i just commented it...It worked!!!
if the problem not solved, try to use IE or FireFox, don't use Chrome because it is not CORS enabled

Auth0 NodeJS Authentification Refused using npm request

I'm facing a problem, I tried to connect to Auth0 API to enable a strong identification on my WebApp.
For context :
Front-End : I'm using an angularJS front, and there I implemented the Lock Library to manage the Auth0 popup by following this webapp-specific tutorial.
Back-End : NodeJS & Express server, in order to verify the user's authentification, I use the npm lib "request" to call the Auth0 API.
If i understand well, a click on the auth0 widget sends a request to the specified endpoint URL, and it's received by the back-end:
app.get('/auth0CallbackURL', function (req, res) {
console.log(req.query.code);
var auth0code = req.query.code;
var client_secret = PROCESS.ENV.SERCRETID;
var domain = PROCESS.ENV.DOMAIN;
var client_id = PROCESS.ENV.CLIENTID;
var redirectUrl = PROCESS.ENV.REDIRECTURL;
var request = require('request'); // request-promise
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token?client_id='+client_id+'&redirect_uri='+redirectUrl+'&client_secret='+client_secret+'&code='+auth0code+'&grant_type=authorization_code',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
And then I call request() to get back the access_token and verify the authentification.
request(requestParams, function(err, data) {
if (err) {
console.log('Err:', err);
} else {
console.log('response body: ', data.body)
}
But the only result I get is :
{
"error": "access_denied"
"error_description": "Unauthorized"
}
At the begining i thougt it was my Auth0 configuration that's didn't allow my authentification, but it seems that there are OK.
Thanks in advance for your replies.
As per the page you linked, you need to pass the following information:
client_id=YOUR_CLIENT_ID
&redirect_uri=https://YOUR_APP/callback
&client_secret=YOUR_CLIENT_SECRET
&code=AUTHORIZATION_CODE
&grant_type=authorization_code
in the request body and with a content type of application/x-www-form-urlencoded.
You're setting the content type correctly, but then are passing the data in the URL query component and instead you need to pass it the POST request body.
Using request package you should do the following:
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token',
method: 'POST',
body: 'client_id=' + client_id +
'&redirect_uri=' + redirectUrl +
'&client_secret=' + client_secret +
'&code=' + auth0code +
'&grant_type=authorization_code',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}

Getting angularJS $http.post from nodeJS

Please help me, I would like to get angularJS $http.post parameter that being sent to be processed in nodeJS.
I would like to see whether the parameter (nama, nip, pernr, etc...) was sent successfully, but the result is undefined as shown below :
angularJS code :
// ADMINISTRATOR ========================================
.state('talentapegawai.uploadtalenta.douploadtalenta', {
views:{
"monitorupload": {
url: '/douploadtalenta',
templateUrl: '/progressupload.html',
controller:function($scope, $http, XLSXReaderService){
$scope.prograssing2 = true;
for(var i=0; i < $scope.sheets[$scope.selectedSheetName].length; i++){
$http.post("/execuploadtalenta",{'nama': $scope.sheets[$scope.selectedSheetName][i].nama, 'nip': $scope.sheets[$scope.selectedSheetName][i].nip, 'pernr':$scope.sheets[$scope.selectedSheetName][i].pernr, 'tgl_grade_terakhir': $scope.sheets[$scope.selectedSheetName][i].tgl_grade, 'singkatan_talenta': $scope.sheets[$scope.selectedSheetName][i].talenta_abbr, 'talenta': $scope.sheets[$scope.selectedSheetName][i].talenta, 'mulai':$scope.sheets[$scope.selectedSheetName][i].mulai, 'akhir':$scope.sheets[$scope.selectedSheetName][i].akhir})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
}
$scope.prograssing2 = false;
}
}
}
})
NodeJS code (express) :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/execuploadtalenta', requireLogin, function (req, res) {
console.log("NILAI REQUEST : "+req.body.nama); -->return undefined
console.log("NILAI REQUEST : "+req); -->return [object, object]
});
server.listen(3333);
First of, Tell body-parser to parse json requests:
app.use(bodyParser.json({limit: '10mb'}));
Its also a good practice to limit the size of json objects
Then, You should be able to read the body as a JSON object.
Take a troubleshooting tip, just to make sure what you get in the body is correct, you can print it as string:
console.log(JSON.stringify(req.body));

Nodejs Express 4 routes not working after changing server to https

I'm using the mean stack (angular v1.4.7, node v0.12.7, express 4.9.0) for my project.
Recently, i adquire ssl certificates and install them on the server, so i had to change my http requests to https.
I also change the nodejs server to requires https instead of the http, but the express routes stopped working and every request is returning net::ERR_CONNECTION_CLOSED. Here is some examples:
Request on angularjs:
$http({
url: "https://www.urbs.pt:3000/auth/isauth",
method: "GET",
withCredentials: true
}).success(function (data, status, headers, config) {
$scope.isloggedin = data;
}).error(function (data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
I'm running my nodejs server with express on port 3000 using https
var authenticate = require('./routes/authenticate');
var options = {
key: fs.readFileSync(pathtokey),
cert: fs.readFileSync(pathtocertificate),
ca: fs.readFileSync(pathtoCA),
requestCert: true,
rejectUnauthorized: false
};
var app = express();
var https = require('https').Server(options,app);
/* this part is initialized on bin/www
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
*/
app.use('/auth', authenticate);
If i use http protocol on the angularjs request, and require http on nodejs everything is working as expected, so i guess that the problem is with the https request. I also confirmed that the options configurations are correct.

How to simulate curl command with Angular

I have this curl command that I would like to simulate with angular:
curl -k -F fieldName=#data.json -u username:Password url
At the moment I went about doing an angular post. However, I run into the problem of authentication. There is no parameter for me to put the user id and password.
Angular code:
$scope.postCall = function () {
$scope.ngResult = "clicked";
var paramsJson = {
"imessageIdT": $scope.messageIdT,
"ilobT": $scope.lobT,
"iregionIdT": $scope.regionIdT,
"iassetClassT": $scope.assetClassT,
"additionalInfoT": $scope.additionalInfoT
};
var config = {
paramsJson: paramsJson
};
$http.post("WEBSITE", paramsJson, config)
.success(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST SUCCESS", data, status, headers, config);
//$scope.ngResult = "Yes";
})
.error(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST ERROR", data, status, headers, config);
//$scope.ngResult = "No";
});
};
Assuming basic authentication, not tested, this might work:
var username = "...", password = "***";
var config = {
headers: {
Authorization: "Basic " + window.btoa(username+":"+password)
},
method: "get", // or "post",
url: "destination.com"
};
$http(config).success(function(){
// on success
}).error(function(){
// on failure
});
The only thing I'm not certain about is window.btoa, if it's an RFC2045-MIME compliant variant of Base64, then you're good.
But my example is an over-simplification. Essentially, you should determine the authentication scheme supported by the server. It could be any one the following specified by IANA:
Basic
Bearer
Digest
HOBA
Negotiate
OAuth
Depending on the required scheme, you should compose the request header accordingly.
This depends on the api you are connecting to. Usually you would log and the server will return you an authentication token on the headers of the response.
1 Basic auth Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
2 Aoth2 Authorization: Bearer mF_9.B5f-4.1JqM
So you will need to add this header to your request:
$http.post("WEBSITE", paramsJson, angular.extend({}, config, {headers: {
'Authorization': token}}))
If the request is to another domain you should use jsonp.

Resources