I am trying to use ajax variable from node js but I have no idea how to.
const express = require('express');
const app = express();
app.listen(8080, function() {
console.log('Listening on 8080.');
});
app.get('/', function(req, res) {
res.sendFile(__dirname '/search.html');
console.log('req.params:', req.params); //req.params: {}
});
Above code is my server.js
<script>
function postData() {
var country = document.getElementById("Country").value;
console.log(country);
$.ajax({
type: "GET",
url: 'http://localhost:8080/',
data: country,
dataType:'text',
success: function(data) {
console.log('success data: ', data);
}
});
}
</script>
search.html
CodePudding user response:
Assuming what you're trying to do is to pass the country
value in your Ajax call and then get access to that value on the server, then you need to put the country into the URL so your server can get it out of the URL.
With $.ajax()
you can pass an object and then jQuery will automatically generate a query string of the form key=value
. Or, you could directly add it to the URL as part of the path. Here's how you would do it as a query string:
function postData() {
var country = document.getElementById("Country").value;
console.log(country);
$.ajax({
type: "GET",
url: 'http://localhost:8080/',
data: {country: country},
success: function(data) {
console.log('success data: ', data);
}
});
}
This will create a URL such as:
http://localhost:8080/?country=USA
Then, on your server, you can use req.query.country
to get the value:
app.get('/', function(req, res) {
console.log(req.query.country);
res.sendFile(__dirname '/search.html');
});
You could also create URL such as:
http://localhost:8080/usa
And, make the request to that URL. To receive that on your server, you can do this:
app.get('/:country', function(req, res) {
console.log(req.params.country);
res.sendFile(__dirname '/search.html');
});
Note, this is what I refer to as a wildcard route because it matches ANY top level path which can interfere with your ability to use other top level URLs on your server. I would recommend not using top level wildcard URLs. You could add a path prefix like this:
http://localhost:8080/country/usa
And, then use this:
app.get('/country/:country', function(req, res) {
console.log(req.params.country);
res.sendFile(__dirname '/search.html');
});
Then, it won't interfere with other top level URLs your server may want to use.