I'm having trouble with an XHR Request, for some reason my server is not receiving my files:
Here is my angular service update algorithm:
var update = function(id, name, file) {
var formData = new FormData();
formData.append('name', name);
formData.append('img', file);
return $http({
method : 'PUT',
url : '/albums/' + id,
data : formData,
headers : {'Content-Type': undefined},
transformRequest : angular.identity
});
};
On my laravel controller I just have:
public function update($id) {
return Response::json(Input::hasFile('img'));
}
The file is obviously there, why can't I retrieve it in my backend?
This is my request info:
Remote Address:[::1]:8000
Request URL:http://localhost:8000/albums/1
Request Method:PUT
Status Code:200 OK
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:13811
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryJ46EVSBw57RaVu7x
Cookie:_token=eyJpdiI6IkkzSXVmdnhubFFlVnlzSnZNWVFzVWk3ZlVKSFRDNFFlNndJWUVsVGNVU2c9IiwidmFsdWUiOiI5OG5PamUrVGZkZGx0ajZONklWajJ2OTM3MWlRd2tGZ2g5S2Jja1RhVjJ4Q1wvYk9xQTB4TlRKUWxkWmdvRm1EcHlzTGRjSEdzN2U5TWNPYWxEYVExVUE9PSIsIm1hYyI6IjA4NTY0ZTlmMjAyNTk3NGQxMmFhODIxMTU3NGNiYjQ4ZDA3OTgxMTA3Yzk1MmVkNmJkMGNkYjUyMmNhMzZkNzQifQ%3D%3D; laravel_session=eyJpdiI6IjRISElnWjd3ZlwvY2k1Z1pvOERWOGxyVHlaQzEwRmlqY1FiV0tNNzZEbEs4PSIsInZhbHVlIjoiYnp4UzVqOFoxMm5MMXhQdzJhVFphSkgrRGh2b2plYXhjdXpTamJ0UjVYdGdxS0puQmpPVXhObEtyb1I3XC9HQnRFdnBMWXV0MzRmWXAybGRySGRvXC9vUT09IiwibWFjIjoiMGQ1NzUyYTBjZmU3NzQ3ZDBkYjg5ZWViOGZmYzg3ZDY1ODg0N2JmNDg1NmQyNmMwZDcxMDE5NzcxZjIxM2MxMiJ9
Host:localhost:8000
Origin:http://localhost:8000
Pragma:no-cache
Referer:http://localhost:8000/Admin/Client
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
Request Payload
------WebKitFormBoundaryJ46EVSBw57RaVu7x
Content-Disposition: form-data; name="name"
Some Weird Album
------WebKitFormBoundaryJ46EVSBw57RaVu7x
Content-Disposition: form-data; name="img"; filename="derpino.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryJ46EVSBw57RaVu7x--
Response Headers
Cache-Control:no-cache
Connection:close
Content-Type:application/json
Date:Wed, 29 Oct 2014 12:47:20 GMT
Host:localhost:8000
Set-Cookie:laravel_session=eyJpdiI6IlQ4WlFOaG1keVhXVlA1dlluNWFZZGlMcmRQNGM3bThCRjZ6cnh4ZlorcWs9IiwidmFsdWUiOiJOZkJXNXBJQTVSTGZzWHJ4alg1SXBoN0Q2ekR6UVpnWThKQ0c4MXZOQlc1RUhNMUUraUZSTlpPYTlPTFdLQXpiYTJONkRvb29WN1djVlZkSGdaWStjQT09IiwibWFjIjoiOWI5MzEwODE2YTZlM2EzODMwZDE1YzI4YmE4M2NiYWJjMTRjMDEzOGI3YjA4NmRlMGU5NDBlZWEyMzI4MGQ3MCJ9; path=/; httponly
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.5.11
I found the error! Apparently I can not send a file with the PUT method, I changed the method to POST and It works. In both the service and the laravel route
var update = function(id, name, file) {
var formData = new FormData();
formData.append('name', name);
formData.append('img', file);
return $http({
method : 'PUT',
url : '/albums/' + id,
data : formData,
headers : {'Content-Type': undefined},
transformRequest : angular.identity
});
};
Related
var dataObject = {
appId: $scope.appId
};
$http({
url: "/mockData/searchResults.json",
method: "POST",
params: dataObject,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data, status){
$scope.results = data;
}).error(function(data, status){ })
The below is the error in network
Remote Address:127.0.0.1:9000
Request URL:http://localhost:9000/mockData/searchResults.json?appId=546
Request Method:POST
Status Code:404 Not Found
Response Headers
Connection:keep-alive
Content-Length:51
Content-Type:text/html; charset=utf-8
Date:Fri, 07 Oct 2016 13:58:15 GMT
X-Content-Type-Options:nosniff
Request Headers
Accept:application/json, text/plain, /
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Host:localhost:9000
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/42.0.2311.152 Safari/537.36
Query String Parameters
appId:546
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
I'm trying to do requests to a RestAPI coded with Codeigniter 3. Access-Control-Allow-Origin and Access-Control-Allow-Headers are set to "*". The API has been successfully tested on Postman.
I'm coding a Web App using AngularJS, and trying to do requests to that API. The following code works properly:
api_service.getUsers = function() {
return $http({
method : 'GET',
url : url + '?dd-api-key=' + api_key
});
}
As this other code functions well too:
api_service.getUsers = function() {
return $http.get(url + '?dd-api-key=' + api_key);
}
But I need to send the API key as a header and not in the URL. So I wrote the function this way:
api_service.getUsers = function() {
return $http({
method: 'GET',
url: url,
headers: {
'accept': undefined,
'dd-api-key': api_key
}
});
}
That code doesn't work. Google Chrome console displays me this:
OPTIONS http://www.myweb.com/api/v1/users
XMLHttpRequest cannot load http://www.myweb.com/api/v1/users. Invalid HTTP status code 403
And at the network tab it shows that the request uses a method type 'OPTIONS', not a 'GET' method.
The Response Headers are:
Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Language:es-ES
Content-Length:45
Content-Type:application/json; charset=utf-8
Date:Wed, 25 Mar 2015 01:45:09 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2
And the Request Headers are:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Access-Control-Request-Headers:dd-api-key
Access-Control-Request-Method:GET
Connection:keep-alive
Host:www.myweb.com
Origin:http://127.0.0.1:55652
Referer:http://127.0.0.1:55652/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Excuse me if my english is not correct.
Many thanks.
you should add header with this:
$http.defaults.headers.common.dd-api-key = api_key;
You can add it in some config as global.
This is my web api method:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<HttpResponseMessage> Register([FromBody] string data)
{
//data is always null
}
AngularJs side:
try {
var postObj = new Object();
postObj.UserName = $scope.RFId;
... Shortened for clarity...
postObj.UserType = $scope.userType;
//var validJson = JSON.stringify(postObj, "\t");
//validJson = '"' + validJson + '"';
postObj = '"' + postObj + '"';
$http({
method: 'POST',
url: 'http://localhost:65337/api/Account/Register',
data: postObj,
headers: {
'Content-Type': 'application/json'
}
}).then(function (result) {
console.log(result);
}, function (error) {
console.log(error);
});
Result:
WebApi does not recognize any of the data or returns 0.... and this is what fiddler catches as my post:
POST http://localhost:65337/api/Account/Register HTTP/1.1
Host: localhost:65337
Connection: keep-alive
Content-Length: 82
Accept: application/json, text/plain, */*
Origin: http://localhost:65337
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36
Content-Type: application/json
Referer: http://localhost:65337/WebApp/index.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
0=%22&1=%5B&2=o&3=b&4=j&5=e&6=c&7=t&8=+&9=O&10=b&11=j&12=e&13=c&14=t&15=%5D&16=%22 // <- Not sure what my post data is formatted like so...
Any help or directions would be greatly appreciated. Thanks
You need to encode your data, look at my article about how to use Web API 2 with AngularJS.
I am new to azure blob storage and I am trying to upload image to blob storage. I am using angular at client end and uploaded image with following headers :
'Content-type'
'x-ms-blob-type'
'Content-Length'
my blob is saved and i can see it in Azure Portal. But I am not able to see images. I am unable to understand the reason.
Link of my client is http://educms.azurewebsites.net/#/pages/results
There is no button. as soon as you select an image file, it will get uploaded. You can see the uploaded file at https://hobcity.blob.core.windows.net/images2/filename.extension
Upload Code of AngularJs
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
var size = files[0].size;
var name = files[0].name;
var type = files[0].type;
var postData = {"name" : name};
postData.containerName = 'images2';
DataService.save('/tables/results/', postData).then(function(data){
var header = {
'Access-Control-Allow-Origin': '*',
'Content-type' : type,
'x-ms-blob-type' : 'BlockBlob',
'Content-Length' : size
}
var url = data.imageUri
var queryString = data.sasQueryString
var uploadUrl = url+ '/' + name + '/?'+queryString
$http.put(uploadUrl, fd, {
headers: header,
transformRequest: angular.identity
}).success(function(data){
console.log(data)
}).error(function(err){
console.error(err);
});
});
}
HTML :
code can be seen live at http://educms.azurewebsites.net/scripts/controllers/results.js
Anyone know what's wrong ?
So I uploaded a simple text file and traced the request through Fiddler. Here's what I saw:
PUT http://hobcity.blob.core.windows.net/images2/simpletextfile.txt/?se=2014-08-11T17%3A13%3A52Z&sr=c&sp=w&sig=SlY7wURwfSjM72Hw22507OHpnaCC1Ky6POk6hhR6fbU%3D HTTP/1.1
Accept: application/json, text/plain, */*
Access-Control-Allow-Origin: *
Content-Type: text/plain, multipart/form-data; boundary=---------------------------7de26921205a0
x-ms-blob-type: BlockBlob
Referer: http://educms.azurewebsites.net/#/pages/results
Accept-Language: en-US
Origin: http://educms.azurewebsites.net
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: hobcity.blob.core.windows.net
Content-Length: 254
DNT: 1
Connection: Keep-Alive
Pragma: no-cache
-----------------------------7de26921205a0
Content-Disposition: form-data; name="file"; filename="simpletextfile.txt"
Content-Type: text/plain
https://hobcity.blob.core.windows.net/images2/Add-Item.png
-----------------------------7de26921205a0--
I believe the reason you're running into the issue is because you're uploading the file as is (see your Content-Type is multipart/form-data) and this is corrupting the data. What you would need to do is read the file contents into a byte array and then upload that byte array. If you search for HTML 5 File API, you will find examples of how to read a file using JavaScript. Also I wrote a blog post about uploading files in Azure Blob Storage using JavaScript which you may find useful: http://gauravmantri.com/2013/12/01/windows-azure-storage-and-cors-lets-have-some-fun/ (though this post make use of jQuery instead of Angular but should give you some idea).