I'm using NodeJS with Express. How can I tell the difference between an ordinary browser request and an AJAX request? I know I could check the request headers but does Node/Exprsss expose this information?
Then add the following code into it: Create ajax get request for fetch data from mysql database in node js app: Create ajax post request send data into from mysql database and display response data into html page in node js app: Create get and post request routes; so visit routes open server.js file; Then add the following routes into it:
Navigate to where you’d like your project to reside, then run the following command: $ express node-express-ajax-craigslist CD into the newly created directory and install the node modules: $ cd node-express-ajax-craigslist $ npm install Aside for the installed node modules/dependencies, your project structure should look like this:
Open main.jsand look at the following code: $.get('/searching',parameters,function(data){$('#results').html(data); This is the actualAJAX request. As I stated before, we pass the parameters(which is an object) to the server side.
Main.js (client-side) redux Open main.jsand look at the following code: $.get('/searching',parameters,function(data){$('#results').html(data); This is the actualAJAX request. As I stated before, we pass the parameters(which is an object) to the server side.
Most frameworks set the X-Requested-With
header to XMLHttpRequest
, for which Express has a test:
app.get('/path', function(req, res) { var isAjaxRequest = req.xhr; ... });
In case the req.xhr
is not set, say in frameworks such as Angularjs, where it was removed, then you should also check whether the header can accept a JSON response (or XML, or whatever your XHR sends as a response instead of HTML).
if (req.xhr || req.headers.accept.indexOf('json') > -1) { // send your xhr response here } else { // send your normal response here }
Of course, you'll have to tweak the second part a little to match your usecase, but this should be a more complete answer.
Ideally, the angular team should not have removed it, but should have actually found a better solution for the CORS' pre-flight problem, but that's how it rests now...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With