PUT request in node.js using $http - angularjs

I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated
vm.approveUser = function(user_id){
console.log('in approveUser');
console.log('user_id', user_id);
$http({
method: 'PUT',
url: '/admin/approve',
data: user_id
}).then(function(){
console.log('back from the /approve');
vm.getRequests();
}); //end .then function
}; //end approveUser

Try simplifying the request and add a return statement. See if it resolves.
vm.approve = function(user_id) {
var url = '/admin/approve';
return $http.put(url, user_id)
.then(function(resp) {
vm.getRequests();
})
.catch(function(error) {
})
.finally(function() {
});
};

Related

How to fix $http GET request

Cannot GET the end point despite passing parameter
Trying to pass an id to the end point for a GET request
controller.js
var vid = $routeParams.vidId //get the video id
console.log(vid) //works
$http({
method:'GET',
url:'/thread/',
params:{vid_id:vid},
}).then(function(success){
console.log('success')
}, function(error){
console.log('error')
})
server.js
app.get('/thread/:vid_id', function(req,res){
console.log(req.params.vid_id)
})
I would expect seeing the vid_id on the server console but instead I am getting a 404 error.
angular.js:13531 GET http://localhost:5000/thread/?vid_id=5cb01f6b03fb0b3e6c2abf7f 404 (Not Found)
You are using the params property on $http, which is meant for appending query string parameters to a URL (eg. ?vid_id=123).
You instead need to dynamically set the URL that you are calling, something like this:
var vid = $routeParams.vidId //get the video id
console.log(vid) //works
$http({
method:'GET',
url:'/thread/' + vid // <==== HERE
})
.then(function(success){
console.log('success')
}, function(error){
console.log('error')
});
If that doesn't work, try to make your server display some text on the endpoint instead of just doing a console.log():
server.js
app.get('/thread/:vid_id', function(req,res){
res.send("test");
console.log(req.params.vid_id)
})
Thank you #nevada_Scout:
I modified you suggestion to work like this:
$http({
method:'GET',
url:'/thread/' +JSON.stringify(vid),
}).then(function(success){
console.log(success)
}, function(err){
console.log(err)
})
Problem solved.

ExpressJS IP and AngularJS $http get

I'm trying to learn ExpressJS and I'm having trouble getting IP address from an Express route to display in the browser via Angular controller.
I'm using 2 Nodejs modules (request-ip and geoip2) to get the IP and then lookup geolocation data for that IP. Then trying to use Angular to display the geolocation data in the browser using an Angular $http get call.
My Express route for the IP:
// get IP address
router.get('/ip', function (req, res, next) {
console.log('requestIP is ' + ip);
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
//return res.status(400).json({error: 'Something happened'});//default
return res.sendStatus(400).json({error: 'Something happened'});
}
else if (result) {
return res.send(result);
}
});
});
And my AngularJS controller code:
function MainController($http) {
var vm = this;
vm.message = 'Hello World';
vm.location = '';
vm.getLocation = function() {
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
};
};
The Hello World message displays but not the location...? I can also go to localhost:8000/ip and see the JSON result. The result doesn't appear in Chrome's console either. The result is a json object like this:
{"country":"US","continent":"NA","postal":"98296","city":"Snohomish","location":{"accuracy_radius":20,"latitude":47.8519,"longitude":-122.0921,"metro_code":819,"time_zone":"America/Los_Angeles"},"subdivision":"WA"}
I'm not sure why the Hello Word displays and the location doesn't when it seems that I have everything configured correctly... so obviously I'm doing something wrong that I don't see...?
You have initialised 'vm.location' as a string when in fact it is a JSON object.
vm.location = {};
You need to adjust the url paramater in your request to:
url: '/ip'
As you are sending back JSON from Express.js, you should change your response line to:
return res.json(result);
Do you call vm.getLocation() somewhere in your code after this?
The data you need is under result.data from the response object.
Also in order to display the data in the html you have to specify which property to display from the vm.location object (vm.location.country, vm.location.city etc..).
From angular docs about $http:
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Is this express js and angular hosted on the same port? If so please replace your
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
with
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
It may be considered as CORS call and you have it probably disabled.
You can also specify second function to then (look code below) and see if error callback is called.
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
}, function (error) {
console.log(error);
});

Creating custom header for $http in AngularJs

In my controller i want send a request using get method if $http, in that get method i want to send the sessionID in headers. Below am giving the code snippet please check.
this.surveyList = function () {
//return session;
return $http.get('http://op.1pt.mobi/V3.0/api/Survey/Surveys', {headers: { 'sessionID': $scope.sessionid}})
.then(function(response){
return response.data;
}, function(error){
return error;
});
}
but this is not working when i send this vale in backend they getting null.
So how to resolve this.
we have a issue where the api is getting called twice from angular , however it works only once when called with the POSTMAN. And here with the custom header passed to the api, the action is called twice. What could be the reason for it?
Try in this way,
$http({
method: 'GET',
url: 'http://op.1pt.mobi/V3.0/api/Survey/Surveys',
headers: {
'sessionId': $scope.sessionid
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs,
// or server returns response with an error status.
});

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

AngularJS $http ajax request is not asynchronous and causes page to hang

I have a service where I am pulling data from server. When I click the button to send out the request to server through this service, the window freezes until I receive a response from server. Is there anything I can do to make this request asynchronous ?
Here is my service.
app.factory('service', function($http) {
return {
getLogData : function(startTime,endTime){
return $http({
url: baseURL + 'getLogData',
method: 'GET',
async: true,
cache: false,
headers: {'Accept': 'application/json', 'Pragma': 'no-cache'},
params: {'startTime': startTime , 'endTime': endTime}
});
}
};
)};
HTML.
<button ng-click="getData()">Refresh</button>
<img src="pending.gif" ng-show="dataPending" />
Code
$scope.getData = function(){
service.getLogData().success(function(data){
//process data
}).error(function(e){
//show error message
});
}
While there is some argument about the pros and cons of your approach, I am thinking that the problem is answered here: AJAX call freezes browser for a bit while it gets response and executes success
To test if this in fact part of the problem, dummy up a response and serve it statically. I use Fiddler or WireShark to get the response and then save to a file like testService.json. XHR and all of it's various derivatives like $HTTP $.ajax see it as a service though the headers might be slightly different.
Use the success promise, and wrap up the log data in a set of objects that you can attach to a $scope.
So instead of having your service have a blocking method, have it maintain a list of "LogEntries".
// constructor function
var LogEntry = function() {
/*...*/
}
var logEntries = [];
// Non-blocking fetch log data
var getLogData = function() {
return $http({
url : baseURL + 'getLogData',
method : 'GET',
async : true,
cache : false,
headers : { 'Accept' : 'application/json' , 'Pragma':'no-cache'},
params : {'startTime' : startTime , 'endTime' : endTime}
}).success(function(data) {;
// for each log entry in data, populate logEntries
// push(new LogEntry( stuff from data ))...
};
}
Then in your controller, inject your service and reference this service's log data array so Angular will watch it and change the view correctly
$scope.logEntries = mySvc.logEntries;
Then in the HTML, simply do something over logEntries:
<p ng-repeat="logEntry in logEntries">
{{logEntry}}
</p>
use this code to config
$httpProvider.useApplyAsync(true);
var url = //Your URL;
var config = {
async:true
};
var promise= $http.get(url, config);
promise.then(
function (result)
{
return result.data;
},
function (error)
{
return error;
}
);

Resources