最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make ajax getpost request in express server? - Stack Overflow

programmeradmin2浏览0评论

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 = "/";

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);
      }
    });
}

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);
      }
    });
}

Share Improve this question asked Oct 6, 2015 at 7:04 SomeoneSomeone 1572 gold badges3 silver badges10 bronze badges 2
  • possible duplicate stackoverflow.com/questions/19074727/… – Muhammad Usman Commented Oct 6, 2015 at 7:11
  • 2 No. That's not the reply I'm looking for – Someone Commented Oct 6, 2015 at 13:52
Add a comment  | 

4 Answers 4

Reset to default 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);
});

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.

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.

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);
});
发布评论

评论列表(0)

  1. 暂无评论