
This assumes you are already familiar with Express. If not, check out my article FreeKB - Node.js - Getting Started with Client Server Express on Docker.
req.query can be used to return URL parameters. Let's say you have the following Express app and you submit a request to the / endpoint with URL parameter foo=bar (e.g. http://www.example.com/?foo=bar)
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
console.log(req.query)
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
Running this app should return something like this in the console log.
{"foo": "bar"}
And here is now you can return a specific request URL parameter, "foo" in this example.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
console.log(req.query.foo)
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
And you probably should have an if / else statement to determine if the URL parameter exists.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
if (req.query.foo == undefined) {
console.log("req.query.foo is undefined")
} else {
console.log(req.query.foo)
}
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
Be aware that if you are using a Node.js client/server model, you can use the above in server, but in client, you'd go with Javascript, something like this.
const url = window.location.href
Or, you can include parameters in a Javascript script tag.
<script src="example.js" foo="bar"></script>
And then access the value like this in Javascript or Node.js client.
const foo = document.currentScript.getAttribute('foo');
Did you find this article helpful?
If so, consider buying me a coffee over at