Angularjs POST request status pending - angularjs

I need your help, dunno no how to solve it, I'm using MEAN stack for simple app, that has a field with input tag inside and when i fill it the data is sending to server and save in db, the problem is that post request cant reach the server.
heres is my post:
$http({
method: 'POST',
url: 'http://localhost:3000/api/message',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({msg: $scope.message})
}).
success(function(response) {
console.log("Success " + JSON.stringify(response));
}).
error(function(response) {
console.log("Error " + JSON.stringify(response));
});
server side:
app.post('/api/message', function(req,res) {
var message = new Message(req.body);
message.save();
res.status(200);
})
app.get('/api/message', function(req,res) {
Message.find(function(err,message) {
if(err) {
res.send(err);
} else {
res.json(message);
}
})
})
and this is what i get in browser dev tool
Request URL:http://localhost:3000/api/message
Request Headers
!Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/json
Origin:http://localhost:3000
Referer:http://localhost:3000/?
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Request Payload
view source
{msg: "3232"}
msg:"3232"

Following could be the issue
actual request is not being sent from the code or browser is using cached data
some adBlocker or some extension is blocking the request
try removing http://localhost:3000 from the url

Related

how to get form data params in headers using angularjs?

i using $http post After success i get the headers in network and it consist of the General,Request Headers,Response Headers,Form Data.
if i using headers() i got response headers but how i get the form data object.
$http({
method: "POST",
url: "http://localhost/demoPaymentGatway/index.html",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
}
}).success(function(data, status, headers, config) {
console.log(headers());
console.log();
}).error(function(r4) {
console.log(headers);
});
Headers:
General:
Request URL:http://localhost/demoPaymentGatway/index.html
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:80
Response Headers:
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Length:1856
Content-Type:text/html
Date:Sat, 06 Aug 2016 12:17:17 GMT
ETag:"740-5396528fb715b"
Keep-Alive:timeout=5, max=100
Last-Modified:Sat, 06 Aug 2016 11:05:25 GMT
Server:Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.5.37
Request Headers:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:700
Content-Type:application/x-www-form-urlencoded
Cookie:PHPSESSID=el7a4qk56sv4ujo4kou0qf43k4
Host:localhost
Origin:null
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36
Form Data:
mihpayid:114256656
mode:
status:failure
unmappedstatus:userCancelled
key:WHlKGc
txnid:264997125205
amount:1.0
addedon:2016-08-06 17:47:58
productinfo:productitem
firstname:vasu
please help me how to get this form data using $http,$resource
If you need to access the form data that was sent in the POST request in the success call back you need to look into the config.data property .
$http({
method: "POST",
url: "http://localhost/demoPaymentGatway/index.html",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
}
}).success(function(data, status, headers, config) {
//This is the post data that was originally sent
console.log(config.data);
}).error(function(r4) {
console.log(headers);
});
For reference please see this link

Angular $resource transformRequest doesn't change Request Header

When I use $resource for a REST login, the transformRequest doesn't add the Authorization header as intended. Using a $.ajax call it does work as intended.
So using:
$scope.login2 = function() {
function setHeader(xhr){xhr.setRequestHeader("Authorization", "Basic " + btoa($scope.gebruikersnaam + ':' + $scope.wachtwoord))}
    $.ajax({type: "POST",  url: "http://localhost:8000/authview/",  beforeSend: setHeader}).
        fail(function(resp){
            console.log('bad credentials.')
        }).
        done(function(resp){
            console.log('welcome ' + resp.email)
        })
}
I get the authorization header added to the request:
Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
But when doing:
$scope.login = function() {
api.auth.login($scope.getCredentials()).
$promise.
then(function(data){
// on good username and password
$scope.gebruikersnaam = data.username;
}).
catch(function(data){
// on incorrect username and password
alert(data.data.detail);
});
};
where "api.auth.login" is defined like:
kmregistratieApp.factory('api', function($resource){
function add_auth_header(data, headersGetter){
var headers = headersGetter();
headers['Authorization'] = ('Basic ' + btoa(data.username + ':' + data.password));
}
return {
auth: $resource('http://localhost:8000/authview/', {}, {
login: {method: 'POST', transformRequest: add_auth_header},
logout: {method: 'DELETE'}
}),
users: $resource('http://localhost:8000/authview/', {}, {
create: {method: 'POST'}
})
};
});
After "headers['Authorization'] = ('Basic ' + ..." (when debugging) I can see it sitting in headersGetter:
headers: Object
Authorization: "Basic YWRtaW46cGFzc3dvcmQ="
accept: "application/json, text/plain, */*"
content-type: "application/json;charset=utf-8"
But it doesn't turn up in the Network tab when inspecting the headers.
So my question is why doesn't the $resource way of working not add the Authorization header?
TransformRequest is not meant to be used to modify headers.
See AngularJS changelog. Scroll a bit downwards and you will see this:
transformRequest functions can no longer modify request headers.
HTTP headers can only be specified when using $http. Example:
$http.post('/someUrl', data, { headers: { 'Authorization': 'Basic'+key } });

Not getting response from Gmail API (Users.messages: send) -- running on mobile device via IonicFramework + AngularJS

I am able to send emails successfully using GMail's API with no issues. The receiver gets the email after a few seconds, but the app doesn't get a response from GMail (i.e., threadid, id, etc...) described here.
I'm running this on a mobile device via IonicFramework w/c uses angularJS by the way. What could be wrong?
$http({
method: 'POST',
url: 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart',
headers: {
'Authorization':'Bearer '+ access_token,
'Content-Type': 'multipart/mixed; boundary="foo_bar_baz"'
},
data: emailStr
})
.success(function(data, status, headers, config){
console.log(data);
})
.error(function(data, status, headers, config){
console.log(data);
});
emailStr contains the base64-encoded message.
This is how the request details look like:
Request URL: https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart
Request Headers
Accept:application/json, text/plain, */*
Authorization:Bearer <<token here>>
Content-Type:multipart/mixed; boundary="foo_bar_baz"
Origin:file://
User-Agent: <<User agent data>>
Query String Parameters
uploadType:multipart
Request Payload
--foo_bar_baz
Content-Type: application/json; charset="UTF-8"
{"raw":"<<encoded string>>"}
--foo_bar_baz--

AngularJS WebApi Authorization header does not appear to be getting passed

I am trying to create a call with AngularJS v1.3.15 into ASP.NET WebAPI (latest from Nuget) to get a list of customers. I can successfully authenticate and get back a token. I add the token to an Authentication header but when I make the call it gets kicked back saying the Authentication header is missing.
The Angular call after I get the token looks like this
$scope.baseUrl = "http://localhost:7800/";
$http({
method: 'GET',
url: $scope.baseUrl + 'customer',
headers: {
'Authorization': $scope.token
}})
I have also tried to utilize the angularjs $resourse
return $resource($scope.baseUrl + 'customer', { }, { 'get': { method: 'GET', isArray: true, headers: { 'Authorization': $scope.token } } });
In the WebApiConfig Register method I have the following setup
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
in a DelegatingHandler I check for the Authorization header like so
var authHeader = request.Headers.Authorization;
From the Angular app it is always null. If I run a check from Fiddler and PostMan I get the Authorization header just fine.
When I press F12 from Chrome and look at the request header these are the results
OPTIONS /customer HTTP/1.1
Host: localhost:7800
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://localhost:63342/Test/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Fixed my issue, after some searches I found that OPTIONS does not seem to be supported out of the box. I found that if I add NuGet package Microsoft.Owin.Cors and then add
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
to the startup.cs file

AngularJS Satellizer jwt CORS issue when authenticated

i'v got weird behaviour of my code. I'm using Satellizer to authenticate user and when user is not authenticated when i execute this code:
$http.get('http://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/somename?api_key=XXXXXXXXXXXXXXXXX')
.success(function (data) {
console.log(data);
});
my request is ok and i get data
headers:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:eune.api.pvp.net
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
but when i authenticate user and try to do same request i get:
XMLHttpRequest cannot load http://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/somename?api_key=XXXXXXXXXXXX. 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.
and headers of this request looks like:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:eune.api.pvp.net
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
my app.config
.config(function ($urlRouterProvider, $stateProvider, $httpProvider, $authProvider, API_URL) {
$urlRouterProvider.otherwise('/');
... some routes ...
$authProvider.loginUrl = API_URL + 'login';
$authProvider.signupUrl = API_URL + 'register';
$authProvider.google({
clientId: 'secret',
url: API_URL + 'auth/google'
});
$authProvider.facebook({
clientId: 'secret',
url: API_URL + 'auth/facebook'
});
// $httpProvider.interceptors.push('authInterceptor');
})
So how should i fix it? I suppose that those headers with Access-Control are the reason, but how should i handle it?
You could try putting the following in the satellizer config:
$authProvider.httpInterceptor = false;
Adding skipAuthorization property in config block might be helpful:
$http.get('http://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/somename?api_key=XXXXXXXXXXXXXXXXX', {
skipAuthorization: true
})
.success(function (data) {
console.log(data);
});
I usually work with the config block by preference. This is how it would look.
//configuration block method:
$http({
method: 'GET',
url: 'http://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/somename?api_key=XXXXXXXXXXXXXXXXX',
skipAuthorization: true
});
Good Luck.
Ok i figured it out. As i supposed Satellizer registers new interceptor, which adds some headers and that's why it doesn`t work. This is satellizer code :
.config(['$httpProvider', 'satellizer.config', function($httpProvider, config) {
$httpProvider.interceptors.push(['$q', function($q) {
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
return {
request: function(httpConfig) {
var token = localStorage.getItem(tokenName);
if (token && config.httpInterceptor) {
token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token;
httpConfig.headers[config.authHeader] = token;
}
return httpConfig;
},
responseError: function(response) {
return $q.reject(response);
}
};
}]);
}]);
i handled it by changing one lane to this:
if (token && config.httpInterceptor && httpConfig.rawReq !== true) {
and i pass in my httpConfig option rawReq: true
but this is not nice. Is there posibility to disable specific interceptor ?

Resources