This may be one of these questions that doesn't need much explanation i just didn't found the answer elsewhere.
I'm pretty new to AngularJS and NodeJS. I did some tutorials and now i try to put something together.
In nodeJS when i do something like this:
app.get('/db-get-extra-bookings', function(req, res) {
res.json({name: "hello"});
});
than in AngularJS i can GET that response and do something with that even if /db-insert-extra-bookings is not an fysical page
return $http
.get(formURL)
.then(function(response){
// some code
});
But when i want to post something from out of AngularJS to my NodeJs environment
return $http
.post(formJson, JSON.stringify(bookings))
.then(function(response){
//some code
});
NodeJS:
app.get('/db-insert-extra-bookings', function(req, res) {
// do something with the request
});
I got a 404 error in my webbrowser console.
base.js:5 POST http://localhost:3000/db-insert-extra-bookings 404 (Not Found)
It sounds like normal behaviour, but why am i getting a 404 error when i POST to a non existing page, and why am i getting the data like i want when i GET from a non existing page?
Do i really need to make an empty page to post to?
I'm not a expert in NodeJS, but if you want to create a route that answer any HTTP method you should use app.all() instead of app.get(). In your code you are just creating a route for GET requests, that is why it works for a GET and don't work for a POST. Check out this reference
Just to clarify, NodeJS endpoints (GET included) do not need to serve an HTML page to work. You can send any type of HTTP response, e.g. plain text, JSON, HTML, etc - with the appropriate 'Content-Type' header.
In NodeJS routes:
app.post('/db-get-extra-bookings', function(req, res) {
res.json({name: "hello"});
});
Now in your angular code (You don't need to JSON.stringify):
// Change localhost:9000 with your hostname
$http.post('http://localhost:9000/db-get-extra-bookings', bookings)
.success(function (data, status, headers, config) {
// console.log(data);
})
.error(function (data, status, headers, config) {
// console.log(status);
});
Also, remember to restart your NodeJS server for the changes to take effect.
Related
I am newbie in firebase admin SDK and trying to get it work on my angularjs app, using and following the steps here and this here:
I have correctly setup my firebase admin SDK and initialized it like this in server.js file on my node server:
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
app.post('/.firebase-user', function (req, res, nex) {
admin.auth().getUser(req.body.uid)
.then(function (userRecord) {
// See the tables below for the contents of userRecord
console.log("Successfully fetched user data:", userRecord.toJSON());
})
res.status(200).send({data: userRecord.toJSON()});
return nex();
.catch(function (error) {
console.log("Error fetching user data:", error);
res.status(117);
return nex();
});
});
now I want to access userRecord.toJSON() inside my controller:
$http.post('/.firebase-user', {uid: firebase.auth().currentUser.uid})
.then(function(response) {
console.log($scope.data, response.userRecord);
});
But it is not printing the userRecord.toJSON(), instead I get true undefined in the console.
Please help me to fetch the info back inside my app. thanks
It looks like there are a few issues with your (Express) app request handler:
In your Angular code, you make a request to the /.fb endpoint but in your server code you are listener on the /.firebase-user endpoint. I assume you want these to both be the same.
Your server code never actually sends a response to the Angular code. I'm surprised your then() completion handler ever actually completes. You should need to explicitly send a response with something like res.status(200).send(userRecord.toJSON()) in the success case and res.status(400).send({ error: error }) in the error case.
You should add a catch() to your Angular code to ensure you are catching any errors or failed requests being made by the server code.
I'm building a WebApp using AngulasJs and Django and I'm currently relying on angular-file-upload to upload image to my api like so :
var uploader = $scope.uploader = new FileUploader({
url: 'http://localhost:8000/image',
headers: { 'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').attr('value')
},
});
The files is uploaded fine but then what I have been unable to figure out is how to get the response from the api (Some data that I need to insert into my html). I first supposed I would be able to register some kind of listener using angular-file-upload module but I didn't find anything that could allow me to do that.
Does the angular-file-upload module provide a way to do this or do I need to rely on an other angularjs functionality ?
Thanks in advance for any help !
Using angular-file-upload-shim, you could declare callback functions like this:
$scope.upload = $upload.upload({
url: 'rs/medias/upload',
method: 'POST',
file: file
}).progress(function (evt) {
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config){
});
Thanks for answering.
I may not understand your response but it seems to me that such callbacks are not available to me when using angular-file-upload.
According to the documentation of angular-file-upload https://github.com/nervgh/angular-file-upload/wiki/Module-API there are no callbacks defined to get api answer on success. The callbacks are triggered either when the the upload is completed or failed but not when the response of the api arrive.
I guess I could use an other way than with angular-file-upload but since I started with it I would prefer to continue with it if a way exist.
WORK AROUND IS AT THE BOTTOM
Original problem
There are question like this all over the web and none of them really have answer for me. I can't get an http PATCH operation to work using angular to save my life. I've implemented $http, with shortcut $http.patch and without using the config object method:PATCH. I've used $resource by adding a custom method. And I've implemented Restangular using their patch and I'm getting the same error. I have the correct Content-Type as suggested in other posts. I think it's safe to say at this point, it's something I'm missing. I'm getting the same "404" message via postman when trying to patch. I can PUT, GET, POST, and DELETE, but not PATCH.
In the following images you can see that the resource exists for GET. But when trying to patch I get 404. Browsing to that endpoint shows the record. Which is stored in Mongodb.
Here's some code snippets:
Resangular GET:
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
Restangular Patch:
var data = {
corporiumId: $scope.newBlock
};
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.patch(data).then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
$http attempt using config object:
controller code:
httpCorporiumSrv.updateCorporiumId('/corporium-mgmnts/' + $scope.params.id, data)
.then(handleUpdateSuccess)
.catch(handleUpdateError);
service code, tried forcing the content-type header but got same result
with or without it:
function updateCorporiumId(url, data) {
return $http({
method: 'PATCH',
url: url,
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
//transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Using the .patch shortcut:
function updateCorporiumId(url, data) {
return $http.patch(url, data, {
transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Thing is I've tried this every which way I know how. I don't even know how to start debugging any more. I'm just getting 404 on a resource that does exist. Any suggestions on what might be happening to my request would be great.
Resolution:
For anyone having this issue, if you could post the fix or what's going on here to this point or PM me that would be awesome I'd like to know. I ended up just using PUT to fix this.
Quick Restangular solution:
Build the url template for findByOne like function using Restangular.one(url, _id) where '_id', is the id of the resource you're looking for. .get() goes out and finds that one resource by said id, which you can populate dynamically however you like. Once you have the one resource with GET copy it with Restangular.copy() which is different from angular.copy as it doesn't bind 'this' to the new object. Change what needs to be changed or added in the new object and then perform a .put() on it.
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
var update = Restangular.copy(res);
// update date corporiumId
update.corporiumId = $scope.newBlock;
// submit new doc with altered value
update.put().then(function() {
console.log('updated')
});
console.log(update)
}, function(err) {
console.log('Restangular failed: ', err)
});
Also because mongo uses _id and Restangular uses id you have to add this to your module
angular.module('corporium-mgmnts').config(function(RestangularProvider) {
RestangularProvider.setMethodOverriders(['put', 'patch']);
// setRestangularFields is required for mongodb
RestangularProvider.setRestangularFields({
id: "_id"
});
});
I am learning sharepoint 2013 for a required incoming project. I has never worked on .net or any other ms technology so i would appreciate if the answers are dumb proof.
I have a server that is running sharepoint 2013 and iis v8.0
Currently i am having some issues, but the main one is that i am trying to access the api service from an angular application. I setted the mapping for intranet to the ip of the server and i can access the api through to the web browser.
I also setted the http response headers to "Access-Control-Allow-Origin" : * in iis. However when i try to access the api using the angular $http object i am getting a message that says XMLHttpRequest cannot load http://x.x.x.x/_api/web. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost : 9000' is therefore not allowed access. The response had HTTP status code 401.
The idea is that the angular application is totally independant of sharepoint and any .net technology. All i want to do is use the rest api to get/edit data.
The request i am making looks like this:
angular.module('angYeoman2App')
.factory('SharePointJSOMFactory', function SharePointJSOMFactory($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
SharePointJSOMFactory.getTasksRESTAppWeb = function() {
var restQueryUrl = "http://x.x.x.x/_api/web";
$http({
headers: { 'Accept': 'application/json; odata=verbose' },
method: 'GET',
url: restQueryUrl
})
.success(function(data, status, headers, config){
console.log(data);
deffered.resolve();
})
.error(function(data, status, headers, config){
console.log('error', data)
deffered.resolve();
});
return deffered.promise;
};
SharePointJSOMFactory.data = function() {
return data;
};
return SharePointJSOMFactory;
});
Any idea what i am doing wrong? I has read that i need to add <% Response.AddHeader("Access-Control-Allow-Origin", "*") %> somewhere, but i don't have any idea to what file.
I also have another problem (not so relevant at this point): When i try to access to a subsite using the ip address it seems it is applying the theme of the parent and it doesn't load the content of the subsite. Any idea why?
Any help is welcome. Tks for your time, have a nice day.
I am trying to do an $http.post and get the response, I tried in several ways but I can't get it working.
The data I am sending (userData) is an json object.
$http.post(url, userData)
.success(function(data, status, headers, config) {
console.log('post success');
console.log('data');
console.log(data);
console.log('status');
console.log(status);
console.log('headers');
console.log(headers);
console.log('config');
console.log(config);
}).error(function(data, status, headers, config) {
console.log('post error');
console.log('data');
console.log(data);
console.log('status');
console.log(status);
console.log('headers');
console.log(headers);
console.log('config');
console.log(config);
});
And I am getting a 404 in status.
Thank you
The "405 Method not allowed" response is because your browser is doing a "preflight" OPTIONS method request via angular $http and your server doesn't support it. There are a bunch of prerequisite responses to enable CORS. If you have access to the server, you can add support for it. One option is to use nginx as a front-end proxy with this kind of configuration:
http://enable-cors.org/server_nginx.html
Read the comments--they are really informative.
Also: see "Preflighted Requests" here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
404 means that the URL you're sending the request to does not exist.
If you're using a sub-directory like mysite.com/angular-site, and you set the URL here to a relative path like "/url/to/api" - you will get to "mysite.com/url/to/path" instead of the correct "mysite.com/angular-site/url/to/path".
So pay attention to that, it might be the problem.