How do I sent additional data to javascript's fetch() function - javascript

I want to use fetch() to query an API endpoint which powers my search page. It returns a list of search results in JSON format.
I also want to pass to the API the current query submitted by the user. The old implementation used jquery and getJSON. Looking at the docs for getJSON, it says that I can pass in a data variable:
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Looking at the docs for fetch, I'm not sure how to pass in data as part of my request. So my question is, how do I pass in a string that will be sent to the server along with my request?
EDIT: I think I can append the query to the request URL, like "/search/?q=Something" and send that. Does anyone have a better way?

If you look at the Body section of the documentation on fetch, it lists several types of values you can use to specify the data sent in your request.
Example using FormData:
var fd = new FormData();
fd.append('q', 'Something');
fetch('/search', {
method : "POST",
body : fd
})
.then(...)
Note that you can't use the body option on GET or HEAD requests (which it seems you may be doing in your case). In that situation, you can build up the parameters using URLSearchParams:
var params = new URLSearchParams();
params.append('q', 'Something');
fetch('/search/?' + params.toString(), {
method: 'GET'
})
.then(...);

You can pass as below
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})

Related

I can not send parameter using GET with jQuery to node js REST API [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

How can i pass a parameters to action method using javascript fetch?

I'm using js fetch to call to an action method(in asp.net mvc),
but I need to pass parameters to the method.
How can I pass this data using fetch?
I'm trying to use this code but the data didn't pass:
fetch(url, {
data: { repositoryName: "dada" }
})
.then(() => {
console.log("test");
});
According to the documentation second parameter shouldn't contain data property.
I guess you need to use body property(you can use JSON string, FormData or URLSearchParams here basing on your needs, see docs):
fetch(url, {
method: "POST",
body: JSON.stringify({ repositoryName: "dada" })
}).then(() => { ... })
Also in this simple example it's possible to simply use query string like this:
fetch(url + '?repositoryName=dada').then(() => { ... })
Note that GET requests cannot have body so if your MVC action is GET action then you have to use query strings like in my second example.

Angular + PHP: Simplest way to POST an object?

I'm studying php and angular. Currently exploring the possibilities to send data to server side using $http service. This is what I came up with and it seem to work, but it doesn't look elegant.
Angular code:
$http({
method: 'POST',
url: 'server.php',
data: "newUser=" + JSON.stringify(user),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function (respose) {
var x = JSON.parse(respose);
console.log(JSON.parse(x));
}).error(function (err) {
console.log(err);
console.log("some kind of error");
});
This is my php code to receive the data and return it:
if (isset($_POST["newUser"])) {
$newUser = $_POST["newUser"];
echo json_encode($newUser);
}
Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Secondly, why do I have to json.parse twice the response in order to convert it back to a JS Object?
Why to I have to specify the headers in order to pass a simple JSON string?
Q1. Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Q3. Why to I have to specify the headers in order to pass a simple JSON string?
In PHP, you have global arrays like $_POST & $_GET to receive the data extracted from the request that are on the form of key=value.
And $_POST is filled when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type.
So in order to use these global arrays, you have to full-fill these two conditions
Okay the alternative way is to use php://input stream to directly read the raw input, so you can send the json string directly.
file_get_contents(“php://input”);

Using fetch instead of jQuery's ajax for a GET API call

I recently found myself converting a function that calls a remote API, from returning a callback to returning a Promise. I thought that'd be a great opportunity to also replace the $.ajax call with a fetch call, as fetch already returns a Promise.
However, this specific call is a GET that actually expects a payload (containing key and return type). Specifically, I call it using:
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: config.serviceUrl,
data: {
apiKey: key,
format: 'json'
}
})
.done(data => {...})
.fail((jqXHR, textStatus, errorThrown) => {...});
However, fetch does not have a data property, and it throws an error if you try to send a body with a GET request (TypeError: Failed to execute 'fetch': Request with GET/HEAD method cannot have body). And according to the Chromium forums this is the expected behavior.
Bear in mind: I have absolutely no control of the external API, so mentioning that sending a payload with GET violates some API protocol, or suggesting I change the underlying call, is not helpful.
Is it possible to use fetch in this scenario? How?
jQuery's ajax function simply appends data to the URL as URL parameters for GET requests:
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Source
Using fetch, you can either do it manually, or you could use an approach similar to that:
var url = new URL("http://youapi.com")
var data = {
apiKey: key,
format: 'json'
}
Object.keys(data).forEach(key => url.searchParams.append(key, data[key]))
fetch(url)
var headers = new Headers();
headers.append("Content-Type", "application/json; charset=utf-8");
fetch(config.serviceUrl + "?apiKey=" + key + "&format=json",
{headers:headers, method:"GET"}
).then(response => response.json())
.then(json => /* do stuff with `json` */)
.catch(err => console.error(err));
is equivalent to current $.ajax() call.

Unable to include file in fetch() POST request

For some reason, I can't get file transfers to work via fetch. My code is really simple:
export function updateProfilePicture(apiKey, userID, picture) {
let data = new FormData();
data.append('picture', picture);
return fetch(`${API_URL}/v1/${ROOT}/update_profile_picture/${userID}`,{
headers: {'Authorization': `Token token=${apiKey}`},
method: 'POST',
data: data
}).then(response => response.json());
}
However, the resulting request does not seem to include any file whatsoever. Am I missing something? In the above example, picture is instance an of File
There could be two reasons:
data field in Fetch API is called body. Use this instead of data property.
(optional) You need to add another header: 'Content-Type', 'multipart/form-data'
Read more about Fetch API:
https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en
https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Fetch polyfill

Categories

Resources