The question is simple: how do I post x-www-form-urlencoded content with Aurelia Fetch client?
I need to make the post to a simple ASP.NET Web API server that is using OWIN and Katana for authentication.
An example of what I have already tried:
var loginDTO = new FormData();
loginDTO.append('grant_type', 'password');
loginDTO.append('email', 'test');
loginDTO.append('password', 'test');
return this.http
.fetch(config.router.token, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: loginDTO
});
Obviously, that didn't work as intended. How is the correct way to go about posting the data presented in the example?
The aurelia-fetch-client is built on Fetch specification, and it seems that Fetch always sends FormData as Content-Type: multipart/form-data.
To get around this, you have to convert the parameters to a query string and then set the content-type to x-www-form-urlenconed. You can use jQuery or a custom function to convert the object to a query string. Like this:
//jQuery.param returns something like ?param=1¶m2=2 and so on
//params = a plain javascript object that contains the parameters to be sent
this.http.fetch(url, {
body: $.param(params),
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(response => {
//your magic here
});
Not a good solution, I know, but that's the easiest way I found so far.
You would use FormData like this:
function sendForm() {
var formData = new FormData();
formData.append('email', 'test#test.com');
formData.append('password', '123456');
http.post(url, formData);
}
Related
I am going to use fetch to post
const token = 'ABCD123:A'
await fetch(path, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: token=encodeURIComponent(token),
});
encodeURIComponent(token) should be ABCD123%3AA
My server should get encoded value, decode value and then store to DB.
But in my api server, it gets non-encode body: token=ABCD123:A
Should server gets encoded value?
And I have tested same encoded value on Postman, my server is getting encoded value.
As my server gets different value, is it Fetch API problem or my fetch request issue?
I think you forgot to make Object for Body,
const token = 'ABCD123:A'
await fetch(path, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
'token':encodeURIComponent(token)
}
});
I have been struggling with image upload for days.
I’m using formdata like this:
let formData = new FormData();
formData.append('file', {
uri: uri,
name: `name`,
type: `image/jpeg`,
});
uri on iOS is something like asset-library://asset/path on Android it is like content://media/external/images/media/25377.
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Authorization': 'Bearer ' + token,
},
};
let response = await fetch("https://myserverurl", options)
I tried every trick reading the image as blob, removing content-type, other libraries like axios, etc…
No matter what I always get back a 400 bad file format error.
Is there something I’m missing with formdata?
(On the backend we use ASP.NET)
We have had a similar issue and were able to solve the issue the following way.
We are using a NodeJS backend (with multer) to handle the file uploads.
Expo - Mobile App Code
// extract the filetype
let fileType = uri.substring(uri.lastIndexOf(".") + 1);
let formData = new FormData();
formData.append("photo", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
We are executing the request with fetch(apiUrl, options).
The uri is the local file path (full URI e.g., file:///...) of the photo in our case and apiUrl is the endpoint of the server-side.
I think the issue might be with the type and format of uri in formdata. Have you tried to use the uri returned by the image picker?
I've seen previous answers on similar queries to this, but i'm still seeing a network error.
Here is my code:
let base64 = require('base-64');
let url = 'https://super_secret.com';
let username = '**supersecret**';
let password = '**supersecret**';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
let APIcall = function checkOrgCode() {
return fetch(url, {
method: 'GET',
headers: headers
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
If i comment out headers.headers and test a simple un-authorized API like https://jsonplaceholder.typicode.com/posts/1 then everything works fine, so clearly authoriation is failing.
When i test my API and headers in postman everything is fine though. I've also tried directly putting the base64 encoded string directly in the headers rather than using the encode function in my code.
Instead of using new Headers() to create the headers, try just a basic object to make life easy:
return fetch(url, {
method: '**PROPER METHOD HERE**',
headers: {
// 'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(username + ":" + password)}`
}
})
erm, so the issue was that the URL i am using isn't in place. I'd been using a hostname file hack which ofcourse works from postman on my PC, but not other mobile devices where i am testing.
I am trying to learn react native application by making a simple login page using api call. Where I will send user name and password to api and it will give me response. But I can't do it. Well I am sharing my code here.....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the way of passing my user name and password to server is wrong. Please give me some idea then I can understand what is wrong here.
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I hope this helps.
You need to Stringify the json data to send request as Post method with Json parameters as you are trying to do...
Here is the example code for how to encode data before requesting for response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Here is the sample code for login :
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
As the commentators before me stated, you simply need to stringify your JSON Body. In general, I' suggest that you incorporate e.g. api sauce into you stack. It is a comprehensive wrapper around the axios library, providing standardized errors and an ok key for quick checks.
Hi am new to aurelia js , i need to upload file to server,am using autrelia js, materializecss and httpClient.fetch for api call. I dont'know how to send file to server.
view :
<input type="file" files.bind="selectedFiles" change.delegate="onSelectFile($event)">
Model :
onSelectFile(e)
{
var myurl = 'http://cdn.dmsapp.tk/file?authToken=bLNYMtfbHntfloXBuGlSPueilaHtZx&type=jpg&name=sibi.jpg&userId=7&organizationId=1&sourceType=USER_UPLOADS';
this.httpValueConverter.call_http(myurl,'POST',this.selectedFiles[],'fileupload',file_upload)
.then(data => {
console.log(data);
if(data.meta && data.meta.statusCode == 200) {
// this.index_lists = data.index.list;
}
}); }
httpservice :
return this.httpClient.fetch('http://api.dmsapp.tk/'+url,
{
method: method,
body : json(myPostData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': this.authorization}})
.then(response => response.json());
looking for a solution.
If it's a file and you are trying to upload a particular media type,
the header 'Content-Type': 'application/x-www-form-urlencoded' does not seem right to me. Have a look at the appropriate media type here:
http://www.iana.org/assignments/media-types/media-types.xhtml
Also, you serialize data to JSON, if your data is binary you will need to change that to a byte array.
You might find some useful info here:
http://www.petermorlion.com/file-upload-with-aurelia/
Also you set a token both in your URL and your header, I'd recommend to set it in the header only.