I need to send both a URL and HTML string in a fetch post request. But I am not sure the proper way to do this. The backend is flexible in how it receives the data, I just don't know whether there is a proper way to do this or whether it doesn't matter and is up to the developer. I have the following HTML and URL:
const myUrl = "https://www.example.com/";
const myHtml = document.documentElement.innerHTML;
Should I send as HTML with a custom header:
fetch("/api", {
method: "post",
mode: "no-cors",
headers: {
"Content-Type": "text/html",
myUrl,
},
body: myHtml,
});
Or JSON:
fetch("/api", {
method: "post",
mode: "no-cors",
headers: { "Content-Type": "application/json" },
body: { myUrl, myHtml },
});
Or does it not matter?
Related
I am trying to send a list of strings with javascript to my java backend but I get unsupported media type response. I have something like this in my backend:
#Path("/myPath")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response myMethod(List<String> myList) {
//do something
}
and my request looks something like this:
var req = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: ["a", "b"]
}
If I use String myList instead of List<String> myList in the backend it works without a problem. I am using javax.ws.rs-api for my rest and I thought it can automatically convert a JSON string to a list, is that not the case?
Try the below
var req = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: JSON.stringify(["a", "b"])
}
I'm trying to parse the body to nodeJS but I get it back in the wrong format.
This is my code:
fetch("http://localhost:5000/email", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: JSON.stringify({ shareUrl: props.shareUrl })
});`
This is how it is parsed when console.log(body.req.shareUrl) in Node
{ '{"shareUrl":"link"}': '' }
this is how I want it back
{ 'shareUrl': 'link' }
EDIT
When I try to send it from Postman it works fine
I get following output:
{ Name: 'jej' }
The Content type:
{ "Content-Type": "application/x-www-form-urlencoded" }
is not ment to send the JSON data in the first place.
If you want to send and receive JSON, change the content type to:
{ "Content-Type": "application/json" }
like:
fetch("http://localhost:5000/email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: { data: json.stringify({shareUrl: props.shareUrl}) }
});`
On server you will find it under req.body.data
I'm trying to figure out how to make the below server call using vue-resource. I not quite sure how to set the header and send data using Vue.$http.post
jQuery.ajax({
url: "http://url/",
type: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
contentType: "application/json",
data: JSON.stringify({
"email": "foo",
"password": "bar
})
})
You should be able to just do this:
Vue.http.post('http://dev-api.languagelink.com/api/auth/login', {
email: 'foo#bar.com',
password: 'foobar',
}).then(res => {
// Handle success response
})
vue-resource will automatically set the Content-Type header and stringifies the payload as JSON.
Try something like this :
this.$http.post('/url', data, {
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(res => {
//do the stuff
});
I'm trying to upload data to dropbox via webbrowser (FF 42.0, PhantomJS 1.9.8) and dropbox v2 api. My function looks like this
function(path, data, callback) {
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
contentType: 'application/octet-stream',
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
},
data: data,
headers: {
"Authorization": "Bearer " + token,
"Dropbox-API-Arg": '{"path": "' + path + ',"mode": "add","autorename": true,"mute": false}',
"Content-Type": "application/octet-stream"
},
success: function (data) {
callback(data);
}
});
}
Even I set the Content-Type at all attributes I can think of to application/octet-stream I get the following error
Error in call to API function "files/upload": Bad HTTP "Content-Type" header: "application/octet-stream
; charset=UTF-8". Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack"
Taking a look at the request in Firebug shows me that the Content-Type was really set to application/octet-stream; charset=UTF-8. When trying text/plain; charset=dropbox-cors-hack as Content-Type the sent request has text/plain; charset=UTF-8, and I get the same error message.
How can I make jquery and my browser to set the headers I need.
EDIT: Same behavior in Chrome
IE works as expected
Technically, Firefox is just adhering to the W3C XMLHttpRequest spec:
http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
Sending anything other than a Blob or ArrayBufferView can cause issues with browsers attempting to encode the data in UTF-8 (to follow the spec).
The right thing to do here is to avoid sending data as a String. Here are two examples of how to avoid this behavior:
// ... file selected from a file <input>
file = event.target.files[0];
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: file,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Or, if you want to send up text, you can UTF-8 encode the text before uploading yourself. A modern way to do this is using TextEncoder:
var data = new TextEncoder("utf-8").encode("Test");
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: data,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Try this...
private void upload(object sender, EventArgs e)
{
OAuthUtility.PutAsync
(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection
{
{"access_token",Properties.Settings.Default.AccessToken},
{ "path", Path.Combine(this.CurrentPath, Path.GetFileName(openFileDialog1.FileName)).Replace("\\", "/") },
{ "overwrite","false"},
{ "autorename","false"},
{openFileDialog1.OpenFile()}
},
callback : Upload_Result
);
}
I am trying to complete a GET request using $http instead of ajax. The call works perfectly with ajax, but when I try to do the same thing with $http I get a 400 (Bad Request) error. I believe I am following the Angular documentation correctly. Any ideas? Hopefully this will also be helpful for others experiencing the same issue.
The ajax code that works:
$.ajax({
type: "GET",
accept: 'application/json',
url: myURL,
headers: {"Authorization": "Basic " + basicKey},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
data: requestPayload,
async: false
}).done(function(serverData) {
console.log(serverData.access_token);
}).fail(function(error) {
console.log(error);
});
The $http code that does not work:
var basicConfig = {
method: 'GET',
url: myURL,
headers: {
'Authorization': 'Basic ' + basicKey,
'Accept': "application/json",
'Content-Type': 'application/x-www-form-urlencoded'
},
data: requestPayload
}
$http(basicConfig).success(function(data, status){
console.log(status);
}).error(function(data, status){
console.log(status);
});
Thanks in advance.
use params instead of data. data is the request body, used for POST requests, whereas params is for query string variables in GET requests.