8

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);
      }
    });
}
Someone
  • 157
  • 2
  • 3
  • 10

4 Answers4

10

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);
});
Community
  • 1
  • 1
Enkode
  • 4,515
  • 4
  • 35
  • 50
  • Hi that solved one of my get request problem; however, I have no ideas why I don't get the data with get request from this link http://jsonplaceholder.typicode.com/comments, it works for /posts in http.get(), but does not work for comments, and it also work if i do it on client view in jquery ajax... :/ can you please explain? – Someone Oct 06 '15 at 08:30
  • There could be several reasons, CORS, incorrect headers... What server are you posting to? Is it your own localhost? You will need to inspect the response to see if the server is responding with an error. – Enkode Oct 06 '15 at 08:34
  • Yea. It is my localhost and don't know why it gives me 404 response :/ – Someone Oct 06 '15 at 08:45
  • First check your express route name. Put in a console.log in your route function to make sure it is making it to the route and then check to make sure your query is working properly. – Enkode Oct 06 '15 at 08:58
  • Just confirm that it is the route. Thank you :D – Someone Oct 06 '15 at 14:47
  • Hi, so i kinda solved that problem, but I did not exactly solve it, because when i opened local host, i can see the result i want, but when i open the static index.html file, i got an error saying: "XMLHttpRequest cannot load file:///homepage. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource." – Someone Oct 09 '15 at 06:16
  • I have included `app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', 'example.com'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); });` in my expressJS code, but I don't why I still have that error – Someone Oct 09 '15 at 06:17
  • Something else is incorrect. It should not be loading from file://homepage, it should be localhost/homepage. I suggest you post all your code to a plunkr so it can be reviewed. – Enkode Oct 09 '15 at 08:31
  • Hi. I already got it. I have to set cross-domain to true in my jquery ajax – Someone Oct 09 '15 at 14:21
  • question explicitly refers the use of express – João Pimentel Ferreira Jul 17 '20 at 22:44
  • @JoãoPimentelFerreira the question refers the use of ExpressJS framework on top of NodeJS and the Answer is for ExpressJS which runs on top of NodeJS so what is your issue? Even the person who asked the question marked it as correct. I am unclear why you have an issue? – Enkode Jul 22 '20 at 17:02
  • @Enkode maybe I am missing something but you are using the package `http`, not `express`. I don't see in your code any `const express = require('express')` (https://expressjs.com/en/5x/api.html) http and express are two different things (https://nodejs.org/api/http.html) – João Pimentel Ferreira Jul 22 '20 at 19:19
2

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.

Jai
  • 74,255
  • 12
  • 74
  • 103
0

Update @Someone, the express framework is very popular to setup a web server in Node. You can use different render engines to render the view and pass information to the user. This is a very simple example from the Express website listening to two urls (/posts and /comments).

var express = require('express');
var app = express();

app.get('/posts', function (req, res) {
  res.send('Render posts!');
});

app.get('/comments', function (req, res) {
  res.send('Render comments');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
Evers
  • 1,858
  • 1
  • 17
  • 18
  • so if i want to make a request from the a real url, what kind of syntax can I use in express? – Someone Oct 06 '15 at 07:07
  • In Node you usually use the http or request module. See my update. – Evers Oct 06 '15 at 07:16
  • @Evers then what is the url user has to type in the browser to get response from this as you suggested. In my opinion the path suggests what operation it has to do like if you have `/home` it returns the home view with use of some view engine. – Jai Oct 06 '15 at 07:20
  • Ah, now I get the confusion. Take a look at Express, express is a web framework. I'll update my answer with an example. – Evers Oct 06 '15 at 07:54
0

Try something like this:

function() {


    // Simple POST request example (passing data) :
    $http.post("/createProject/"+ id +"", {
        projectTitle: pTitle,
        userID      : id
    }).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.getProjects();
        console.log("project created");
        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
 };

Also please note. you will call this from an external JavaScript file. One the express server you will only have "routes" and from external javascript files you can perform HTTP calls on those routes.

Skywalker
  • 4,984
  • 16
  • 57
  • 122