Setting query string using Fetch GET request
Update March 2017:
URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.
The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
However, I'm not sure Chrome supports the searchParams
property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.
Update April 2018:
With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search
instead of looping over all keys and append them
var url = new URL('https://sl.se')
var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]
url.search = new URLSearchParams(params).toString();
fetch(url)
Sidenote: URLSearchParams
is also available in NodeJS
const { URL, URLSearchParams } = require('url');
Fetch request method Get.. How i can get response with query params?
Not enough reputation to add a comment, but, what does the console.log output? I don't expect it to have the updated state value in it because setState doesn't happen instantly. It's batched in react. So, if you call it where you're calling it, you will not get the expected value of this.state.area in the below line.
new URLSearchParams({ input: this.state.area }).toString(),
Instead of the above, try this,
new URLSearchParams({ input: e.target.value }).toString(),
GET with query string with Fetch in React Native
Your first thought was right: just add them to the URL.
Remember you can use template strings (backticks) to simplify putting variables into the query.
const data = {foo:1, bar:2};
fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
method: "GET",
headers: headers,
})
how to pass through parameters using a get/ fetch statement (express)
If it's a get API I think you can add a query param in your client
getItems() {
try {
const email = window.localStorage.getItem("User");
const data = { email };
//I'm adding query params here
fetch(`/profile-account-details?email=${email}`)
.then(recordset => recordset.json())
.then(results => {
this.setState({ AccountDetails: results.recordset });
});
} catch (e) {
console.log(e);
}
}
And in your server code
app.get("/profile-account-details", function(req, res) {
// Get the email from the query params
let email=req.query.email
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.execute("dbo.ProfileAccountDetails", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});
How can I send query parameters using fetch to server?
Query string parameters are part of the request URL.
Try the following to pass latitude and longitude when you do a GET request assuming the endpoint is http://localhost:3000/data?lat=0&long=0
app.get("/data", (req, res) => {
// Add this to retrieve query string values
let latitude = req.query.lat;
let longitude = req.query.long;
// Rest of your code
});
Use fetch to send get request with data object
If I pass the data object as normal in the fetch constructor for a
GET request, would it send the request like the example I gave
'/test/?test=test'
If you want to add query string to a fetch request :
From the SPEC
var url = new URL("https://a.com/method"),
params = {a:1, b:2}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url)
this will produce a request :
Sending query string parameters to php via fetch not working
I recommend you take a look at the MDN Fetch() API documentation. Your fetch()
is missing its headers, its method, a response resolution (first .then()
), and a result resolution (second .then()
).
But, you MIGHT NOT WANT to use fetch()
. Fetch returns the result of the page to the JavaScript, not to the user. The way you're using it, it looks like you just want the user to go to that page directly (in which case, just <a href='?name=matt'>Click Me</a>
).
Ultimately, I think you need to understand that the purpose of fetch()
is to send data to the JS environment, not to reload the page for the user. Anyway, here's how your call would look if it worked...
<script>
fetch('index.php?name=matt', {
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method':'GET',
'body':'',
})
.then((response) => response.text())
.then((responseText)=>{
console.info("Response?");
console.info(responseText); // result: "The name param is received!...(and the rest of your page)
});
</script>
If you wanted to have fetch() return $_GET
and/or $_POST
variables to the JS in a usable fashion, then welcome JSON and json_encode()
into your heart.
Make a new PHP script, userdata.php
, and code it as so...
<?php
header('Content-Type: application/json'); // send JSON header, let page know it's JSON
print(json_encode(['name':$_POST['name']])); // get the name
?>
With this, update your above JS to be...
fetch('http://www.example.com/your/script.php', {
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'method':'POST',
'body':JSON.stringify({'name':'matt'}),
})
.then((response) => response.json())
.then((responseJson)=>{
console.info("Response?");
console.info(responseJson);
});
Notice what I have changed above: I made it use the POST method, which gives you a cleaner way of sending the data (namely using body
, instead of appending it onto the URL, like '?...'
). Your response, also, is .json()
'd, and not .text()
d.
How to pass two parameters to an API 'Get' Request in Javascript/NodeJS
Solution with Query Params
You can pass your parameters as query params
in your GET request URL.
Here is the format of a URL that has multiple query params:
http://localhost:8000/api/likes/user?postId=xyz&userId=123
Here, you can see the ?
symbol which indicates that query params have been started. And, you'll also notice &
used for separating multiple query params. This way, you can send as much as query params you want.
Note: All query params are string
. Query params size can be maximum 1024 characters in your URL.
Here is a sample code for receiving query params from the node.js backend
:
exports.sampleFunction = async (req, res) => {
const postId = req.query.postId
const userId = req.query.userId
// write your code here
}
Here is a sample code for sending the query params from the front-end
using fetch
:
const docs = await fetch(`/api/likes/user?postId=${postId}&userId=${userId}`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
Related Topics
How to Get Visitor's Location (I.E. Country) Using Geolocation
Format Date to Mm/Dd/Yyyy in JavaScript
Parse JSON String into a Particular Object Prototype in JavaScript
How to Use Z-Index in Svg Elements
Why Should I Use a Semicolon After Every Function in JavaScript
JSON.Stringify Doesn't Work with Normal JavaScript Array
Parallel Asynchronous Ajax Requests Using Jquery
How to Compare Two Time Strings in the Format Hh:Mm:Ss
Are There Pointers in JavaScript
How to Add Conditional Attribute in Angular 2
Jquery Selector for Id Starts with Specific Text
Get Protocol, Domain, and Port from Url
Template String as Object Property Name
Detecting iOS/Android Operating System
How to Transpose a JavaScript Object into a Key/Value Array