Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ajax get/post request in express server?

Below is my express server. I am trying to make a get request in ajax, but it turned out failed even though I required jquery at the beginning. It said $ is not defined Other than using jquery ajax, what else can I use to make an API call form RESTful API url?

var express = require('express');
var requestHandler = require('./requestHandler');
var app = express();
var path = require('path');


app.use(express.static(path.join(__dirname, '../client')));
app.get('/homepage', requestHandler.getData);

var port = process.env.PORT || 3000;
app.listen(port);
console.log("Server running at: http://localhost:" + port);

// request handler file:

var express = require('express');
var url = "http://jsonplaceholder.typicode.com/";

module.exports.getData = function (req, res){
    $.ajax({
      method: 'GET',
      url: url+'posts',
      success: function(data) {
        console.log(data);
        res.send(data);
      }
    });
  }
module.exports.getComments = function(userId){
    $.ajax({
      method: 'GET',
      url: url+'/comments',
      success: function(data) {
        console.log(data);
      }
    });
}
like image 677
Someone Avatar asked Oct 06 '15 07:10

Someone


People also ask

Does ajax use POST or GET?

post() methods provide simple tools to send and retrieve data asynchronously from a web server. Both the methods are pretty much identical, apart from one major difference — the $. get() makes Ajax requests using the HTTP GET method, whereas the $. post() makes Ajax requests using the HTTP POST method.

Can I use ajax with Express?

expressjs is serverside code so it can't use jquery ajax like that.

What is ajax POST get?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.


2 Answers

HTTP GET Request in Node.js Express

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});
like image 114
Enkode Avatar answered Sep 22 '22 02:09

Enkode


You need to understand things like:

  1. expressjs is serverside code so it can't use jquery ajax like that.
  2. jQuery.ajax() can only be used at view when you load your page in the browser.

You need to use some view engines like jade to create templates and use routers to push the view in the browser. When you have your view in the browser then you can make a reference to the script file which can contain your ajax code to let you have posts and comments.

More information.

like image 33
Jai Avatar answered Sep 24 '22 02:09

Jai