How to "get" from NodeJS with AngularJS - javascript

I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work
Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
$http.get("localhost:8080/product")
.success(function (response) {
$scope.keys = response;
console.log(response)
})
};
$scope.keyLoad();

I get 404 not found. I figured it would be a cors problem
If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:
$http.get("localhost:8080/product")
That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.

You should use $http service.
For example:
$http({
method: 'GET',
url: '/someUrl'
}).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.
});
Or
$http.get('/someUrl', config).then(successCallback, errorCallback);

Related

CORS enabled on AWS API, but still getting "No Access-Control-Allow-Origin" in Angular

I recently restructured my API on AWS Gateway to make all my Lambda functions use proxy integration - before that, every single parameter was passed in as a path parameter (awful, I know.)
I never had any issues with CORS then, and I've tried several things over the past few hours to fix the issue discussed in the topic line.
First, I used a proxy resource and used an "ANY" method, but when that gave me CORS issues, I enabled CORS on the API method and tried again - still nothing. So, I tried changing it so that it was a "POST" request instead and enabling CORS - still nothing. And I made sure to deploy after every setting change. Then, I got rid of the proxy and instead just made a "POST" method with CORS enabled, and still nothing.
I'm using Angular's http post method.
Edit:
I'm using Angular 1.6.4, and this is the code I'm using to call the API:
this.checkRegistered = function(email){
var data = { Email : email};
var toSend = JSON.stringify(data);
return $http.post('link', toSend);
};
That's in my service for the angular module, and it's being called from this function in the controller:
function CheckIsRegistered(email)
{
return userService.checkRegistered(email).then(function(res){
if (res.data.statusCode === 200){
return res.data.body;
}});
}
I've configured all the parameters so that "Email" is what it should be expecting, and I did replace the word 'link' with the actual link.
When I enable CORS through the console, I assign the headers as follows:
Access-Control-Allow-Headers: 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Origin: '*'
This is especially infuriating because I've actually worked with this exact issue before and solved it fairly easily, but now that I'm using Lambda's proxy integration I've run into this issue again and I can't quite seem to figure it out.
Any help is appreciated.
I figured out the problem - I had to add the headers for CORS to the Lambda response. Here's the code snippet for anyone else having similar problems:
connection.query('arbitrary query', [params], function (error, results, field) {
if (!error)
{
connection.end();
var responseBody = results;
response = { statusCode: 200,
headers: { "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token", "Access-Control-Allow-Origin": "*"},
body: JSON.stringify(responseBody)};
callback(null, response);
}
I put the querying line in there just for context of what "response" is.

Angular http GET 405 (Method Not Allowed)

I'm implementing another function in an application (made with angular), I call an API (made with Lumen) and it returns a 405 error whem i tried in local and "XMLHttpRequest cannot load Response for preflight is invalid (redirect)" when i tried on the server. I read about CORS but it's already implemented, I think if it isn't none of others functions would work.
Another thing, if I make the call with Advanced Rest Client it works fine :(
sorry about my english, i don't speak it so much.
function on application
$scope.agencias = [];
$http({
method: 'GET',
//url: 'http://api-beta.grupoaldorf.com.mx/agencias/',
url: 'http://localhost:8000/agencias/',
headers: agenciaMazda.headers
}).then(function successCallback(response) {
$scope.agencias = response.data;
console.log("regreso del http");
console.log($scope.agencias);
}, function errorCallback(response) {
//callback(false);
});
route on web.php
$app->get('agencias','CitasController#agenciasDisponibles');
controller in CitasController.php
public function agenciasDisponibles(Agencia $agencia){
$fabricante = $this->request->header('Aldorf-App');
$disponibles = Agencia::where('fabricante', $fabricante)->where('mostrar', 1)->select(['codigo', 'nombre'])->get();
return $disponibles;
}
Finally i solved it, it was really dumb, i added a slash at the end of the uri xD it had to be "http://localhost:8000/agencias" instead of "http://localhost:8000/agencias/"

Cross domain HTML parsing using AngularJS [duplicate]

This question already has an answer here:
Why does my JSONP request give me Uncaught SyntaxError: Unexpected token < (less than)?
(1 answer)
Closed 5 years ago.
We are working on java project in which backend is java + spring and fronted is angular 2 + HTML.
I want to do cross domain html parsing but we don't have permission to access external links on server side as we have some security issues for outsite domains, so we have to get the DOM content of link on client side using jquery.
I have tried these:
var url = "http://xyz.aspx";
$http({
method: 'JSONP',
url: url,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).
success(function(response) {
$scope.test = response;
}).
error(function(status) {
//your code when fails
});
The external link which I need to parse contains many href links. I also need to parse content of those links.
Have tried above mentioned code:
getting error in console - Uncaught SyntaxError: Unexpected token < on
xyz.aspx page
What will be best solution to get content of the pages and pass to server side for parsing?
Solution 1)
getting error in console - Uncaught SyntaxError: Unexpected token < on xyz.aspx page
This means that the server callback isn't a valid JavaScript application. Please ensure your server returns a valid JavaScript application. In that way this error will go away. JSONP needs a valid JavaScript application response to make it work. For example this is how a JSONP callback should look like:
jsonCallback(
{
sites: [
{
siteName: "Test"
}
]
}
);
Solution 2)
If your server side does not return a JSON Object try to use a GET request and enable CORS.
$http({
method: 'GET',
url: "http://xyz.aspx",
}).success(function(response) {
$scope.test = response.data;
}).error(function(status) {
//your code when fails
});
Solution 3)
If you are still be unable to add CORS to your backend you could create an PROXY application yourself. This for example is an public CORS Proxy https://crossorigin.me/. Adding an example on how to create a proxy service would be to much. Please research by yourself. There are a lot of examples in the web.
See ng.$http. Your URL is missing the callback parameter,instead of giving like
json_callback: 'JSON_CALLBACK'
Try below way
$http({
method: 'jsonp',
url: 'http://xyz.aspx?callback=JSON_CALLBACK',
params: { name: 'xyz' }
}).success(function(data, status , header, config) {
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});

AngularJS - Stuck Handling response after $resource.save (expecting json)

Hello first of all thanks for your support,
I getting started with angular and I am trying to use conmsume data from an API for my app. I am having a few problems with this.
First of all CORS:
To run local http server I am using the one that comes with node.js (using http-server command).
I am using http://www.mocky.io/ to test the app. I've generated differents (with headers I've found around the net that are supposed to fix it) response there to try to fix CORS (always getting preflight error) but nothing seems to work.
I have added this to my save method (inside a factory):
save: {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*'
}
}
If I use a Chrome extension called CORS I can bypass that and receive response but then I am not able to manage the promise and get the data inside the response. I would like to be able to show the response's json on the view.
$scope.submitForm = function() {
var promise = null;
promise = CheckFactory.save($scope.partner).$promise;
$scope.result = promise.data;
}
This functions sends the data from the form to the factory and perform the request but then I am lost and do not know how to manage the data I need from the response.
Thanks in advance :)
Basically you need to put .then function over your save method call promise. So that will call .then function's once data save request gets completed.
$scope.submitForm = function() {
CheckFactory.save($scope.partner).$promise
//it will called success callback when save promise resolved.
.then(function(data){ //success
$scope.result = data;
}, function(error){ //error
});
}

AngularJS $http.post() firing get request instead of post

i building an API service in angular and laravel, when i firing a GET call to the API everythings work fine, but when i fire POST call the service still use GET method instead of POST.
that is my service:
function LeadsAPI($http,$q,BASE_URL)
{
this.updateLead = function (lead_data) {
var url = BASE_URL+"/leads/update/";
var deferred = $q.defer();
$http.post(url , lead_data).then(function(response){
deferred.resolve(response.data);
});
return deferred.promise;
}
}
i call to this function from a Controller:
LeadsController.$inject = ['$scope', 'LeadsAPI'];
function LeadsController($scope , LeadsAPI)
{
LeadsAPI.updateLead({'lead_id' : res._id, 'the_lead': {'fist_name' : 'asd asd'}}).then(function (res) {
console.log(res);
});
}
i tried pass the parameters as a string ("a=b&c=d...") and added header :
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
in the run function at my App module instantiation but yet, i keep getting 405 (Method Not Allowed) error.
any ideas why and how to solve it? thank you very much all! :)
Seems the question is old and unanswered but google led me here. I hope someone will find this answer useful.
I had the same problem. $http was set to POST but server was returning error from GET request.
After checking the headers in a web inspector it shows the browser actually did two requests:
update/ 301 text/html angular.js:11442
update 405 xhr https://test.site/post/update
The first one is the one from $http and the second one is after a redirect.
As you can see the trailing slash URL is redirected to a non trailing one. With this redirect a POST request gets also changed to GET as well.
The solution is to change your request url to not contain trailing slashes:
url: BASE_URL+"/leads/update",
The GET works fine ... good
The POST returns 405 - Method not allowed
It sounds like it is doing a POST and the server you are posting to does not support POST requests to the endpoint in question
Can you please provide more information, such as the HTTP request and response headers when you make a GET request and the same for the POST request
You can access the header information via the NET tab in Firefox's Firebug or in Chrome console
Be sure that your API method is ready to handle a POST request. Maybe Angular is actually firing a POST request, but your method is expecting a GET.
If you are sure Angular is really firing a GET request instead of a POST for some reason, try to explicitly set the HTTP method on the $http object:
$http({
method: 'POST',
url: BASE_URL+"/leads/update/",
data: lead_data
}).then(function (response) {
deferred.resolve(response.data);
});

Categories

Resources