$http angular pass object? - javascript

Hello how can i pass this object as param in Http with angular?
Because my wcg public void CreateNewAccount(Users us)
$scope.RegisterUser = function(){
var us = {
UserName:$scope.userName,
Password:$scope.password,
UserRoleID:null,
Company:$scope.company,
Terms:$scope.terms,
ID:null,
BuyerID:app.buyerId
};
$http.get(
app.wcf+'/CreateNewAccount'angular.toJson({us:us}))
.then(
function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};

You need to pass your object as params in to the config of the $http.get(url, config) method.
$http.get(app.wcf + '/CreateNewAccount', {params: us})
.then(function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};
That said, you shouldn't be passing this data as a GET request, especially not with a username and password in the query string.

For get, you should use params:
$http({method:'GET', url:'url', params:us})

I'm getting this it seams to call OPTIONS
Remote Address:192.168.58.182:80
Request URL:http://192.168.58.182/ESService/ESService.svc/CreateNewAccount
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,pl;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.58.182
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, Accept
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Allow:POST
Content-Length:1565
Content-Type:text/html; charset=UTF-8
Date:Fri, 30 Jan 2015 14:10:34 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET

Related

jQuery Ajax Form Data settings convert to pure javascript

Found the answer thanks from Patrick Evans:
window.onload = function()
{
var data = new FormData();
data.append("gcd", "gcd");
data.append("name", "name");
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
Here is my Ajax test javascript using jQuery and Pure Javascript Ajax:
window.onload = function()
{
var url = "GRNM";
var data = {
gcd: "gcd",
name: "name"
};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
Pure Javascript Ajax:
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(JSON.stringify(options.data) || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
And this is the result:
jQuery: I could get the value data successfully
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 200
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: keep-alive
Content-Length: 43
Content-Type: application/json
Date: Fri, 27 Aug 2021 06:20:37 GMT
Keep-Alive: timeout=60
Request Headers:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
gcd: gcd
name: name
Pure Javascript: I couldn't get the data
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 400
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: close
Content-Language: en-US
Content-Type: text/html;charset=Shift_JIS
Date: Fri, 27 Aug 2021 06:20:37 GMT
Transfer-Encoding: chunked
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 27
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
{"gcd":"gcd","name":"name"}:
My Spring Boot Controller couldn't find the gcd and name parameter that came from pure javascript because the Form Data format is different. I've also tried to use FormData() but couldn't make it work.
My Form Data becomes like this:
Form Data:
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name: "gcd"
gcd
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name="name"
name
------WebKitFormBoundaryLgD8tjkxnVk4hfiE--
I've also tried changing http_request.send(JSON.stringify(options.data) || null); to http_request.send(options.data || null); but didn't worked.
How can I achieve the same result as jQuery? How can I pass my var data object to controller using Ajax POST same as jQuery?
You need to supply the correct content-type with the correct content.
If you want to send JSON text you have to use application/json content-type
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(options.data));
If you want to use the FormData object you need the multipart/form-data content-type
let fd = new FormData();
for(let key in options.data){
fd.append(key,options.data[key]);
}
//don't need to explicitly set content-type when sending FormData
//it will automatically do that
//http_request.setRequestHeader('Content-Type', 'multipart/form-data');
http_request.send(fd);
If you just want to use your object you will need to convert it to one of the previously mentioned methods or create a param string from it and use application/x-www-form-urlencoded content-type
//builds a param=value&param2=value2 type of string from your options.data object
let paramStrings = [];
for(let key in options.data){
paramStrings.push(`${key}=${options.data[key]}`);
}
let data = paramStrings.join('&');
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.send(data);

400 bad request ajax post request

I'm running into a weird problem, I want to do a POST request in AJAX with the following code:
$('.login-form').on('submit', function(e) {
e.preventDefault(); // to block the behavior from HTML form
$.ajax({
type: "post",
url: "http://localhost:8080/login",
data: JSON.stringify({
username:"lmezkml",
password:"ezaezaeza"
}),
success: function(data, textStatus, jqXHR) {
console.log('success');
},
contentType: "application/json; charset=utf-8",
dataType: 'json'
});
});
Even after following the multiple topics on this problem, i'm still in trouble.
For example, i've tried :
adding dataType: 'json'
adding contentType : "application/json; charset=utf-8"
using XMLHttpRequest()
using $.post
The inspector of Chrome give me :
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/login
Request Method:POST
Status Code:400 Bad Request
**Request Headersview source**
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:45
Content-Type:application/json; charset=UTF-8
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
**Request Payloadview source**
{username:lmezkml, password:ezaezaeza}
password: "ezaezaeza"
username: "lmezkml"
**Response Headersview source**
Connection:close
Content-Type:application/json;charset=UTF-8
Date:Wed, 09 Dec 2015 14:39:11 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Here is my code from server :
#RequestMapping(value="/login", method=RequestMethod.POST, produces={"application/json"}, consumes={"application/json"})
public ResponseEntity<?> hello(#RequestParam("name") String username, #RequestParam("password") String password) {
System.out.println("username : " + username + " password : " + password);
try {
LdapContext ctx = ActiveDirectory.getConnection(username, password);
ctx.close();
}
catch(Exception e) {
//Failed to authenticate user!
e.printStackTrace();
return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(null, HttpStatus.OK);
}
Hope it can help to resolve my problem of 400 bad request.
Thanks in advance.
I think, problem on server.
Try send to server js object, not string, or debug in server.
I've solved my problem thanks to Alex Repeckiy. The real problem was that the data was stored in Body and ive tried to get them by parameter.
If it can help Spring Framework users, i change my function by using #RequestBody instead of #RequestParam.
Thanks !

How to Set value in Http Request Header

I am dealing with cross origin request to access my restful API's,so i want to set field "Authorization" in http request header on every request,but is not going to set in header...so what am doing wrong here?
My app.js
'use strict';
var app = angular.module('samepinch', [
'ngResource',
'ngCookies',
'ui.router',
'toaster',
'ui.bootstrap',
'oc.lazyLoad',
'samepinch.controllers',
'samepinch.directives',
'samepinch.factory',
'samepinch.services',
// Added in v1.3
'FBAngular',
'Config',
'samepinch.login',
'samepinch.item',
'samepinch.common'
]);
angular.module('samepinch.login',[]);
angular.module('samepinch.item',[]);
angular.module('samepinch.common',[])
app.run(function($http)
{
$http.defaults.headers.common.Authorization = '';
// Page Loading Overlay
public_vars.$pageLoadingOverlay = jQuery('.page-loading-overlay');
jQuery(window).load(function()
{
public_vars.$pageLoadingOverlay.addClass('loaded');
})
});
Controller is
angular.module('samepinch.login').controller('LoginController',['$scope','LoginService','$rootScope','$http',function($scope,LoginService,$rootScope,$http){
$rootScope.isLoginPage = true;
$rootScope.isLightLoginPage = false;
$rootScope.isLockscreenPage = false;
$rootScope.isMainPage = false;
$scope.register = function(credentials){
$http.defaults.headers.common.Authorization = 'dfdfdf';
LoginService.post(credentials,function(success){
},function(error){
});
}
}]);
My Service is
'use strict';
angular.module('samepinch.login').factory('LoginService', ['$resource','$enviornment', function ($resource,$enviornment) {
var url = $enviornment.backendurl;
return $resource(url+'authenticate',{},{
query: {
method:'GET',
params:{itemId:''},
isArray:true
},
post: {
method:'POST',
headers: {
'Authorization': 'Basic dGVzdDp0ZXN0',
'Content-Type': 'application/json'
}
},
update: {
method:'PUT', params: {itemId: '#entryId'}
},
remove: {
method:'DELETE'
}
});
}]);
My Http request looks like
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/api/v1/authenticate
Request Method:OPTIONS
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9006
Pragma:no-cache
Referer:http://localhost:9006/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Response Headersview source
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE,PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Wed, 22 Jul 2015 07:52:15 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
So 'Authorization' field is not set in headers..please help me what am i missing here
This log is for OPTIONS request
Request Method:OPTIONS
First you need to setup your server to return 200 OK for OPTIONS call then the POST call with proper parameters will be send
Look for instructions here http://enable-cors.org/ how to configure CORS (including OPTIONS request) on your architecture

Angular $http.post not sending any data

I'm super stuck with trying to simply post JSON data but for some reason it won't work.
angular.module('pocket.controllers', [])
.controller('ArticleList', function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})
When I inspect the request in the Chrome inspector it doesn't seem like any data is actually being posted:
Request URL:https://getpocket.com/v3/oauth/request
Request Method:OPTIONS
Status Code:400 Bad Request
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, x-requested-with, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:getpocket.com
Origin:http://pocket.dev:8000
Pragma:no-cache
Referer:http://pocket.dev:8000/app/index.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
Response Headersview source
Cache-Control:private
Connection:keep-alive
Content-Length:15
Content-Type:text/html; charset=UTF-8
Date:Wed, 24 Jul 2013 17:18:04 GMT
P3P:policyref="/w3c/p3p.xml", CP="ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE"
Server:Apache/2.2.25 (Amazon)
Status:400 Bad Request
X-Error:Missing consumer key.
X-Error-Code:138
X-Powered-By:PHP/5.3.27
X-Source:Pocket
As you can see, the X-Error is "Missing consumer key" which implies the data is not being posted correctly.
Add this line to your code;
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded";
Modified code will be like this;
angular.module('pocket.controllers', []) .controller('ArticleList',
function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})

Got XHR.status 0 while doing http get request through jquery code while HTTP response is 200 ok

I am trying to send get request to REST based API(JAX-RS/Jersey based API) through jquery. Request reaches successfully to API as I have seen in logs and on firebug i saw 200 ok response
below is my jquery based client
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'http://mtnlp.com:8080/restdemo/resources/employee/1',
dataType: "json",
success: function(data){
alert("success");
},
error: function(xhr){
alert("error"+xhr.status);
}
});
});
});
But xhr.status is 0.
MY resource is
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson( #PathParam("empno") int empno) {
JSONObject jObject = new JSONObject();
System.out.println("someone calls me");
switch(empno) {
case 1 :
jObject.put("name", "George Koch");
jObject.put("age", "58");
break;
case 2:
jObject.put("name", "Peter");
jObject.put("age", "50");
break;
default:
jObject.put("name", "Unknown");
jObject.put("age", "-1");
} // end of switch
return jObject.toString();
}
When i use my jersey based client it works fine. but with jquery based client I am facing above issue.
Please find below the request and response headers for HTTP get request
Response Headers
Content-Type: application/json
Date: Tue, 04 Jun 2013 06:38:12 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate Accept-Language en-US,en;q=0.5
Host: localhost:8080
Origin: null
User-Agent: Mozilla/5.0 (Windows NT5.1; rv:19.0) Gecko/20100101 Firefox/19.0

Categories

Resources