How to consume a REST service in node.js from an a

2019-08-31 14:56发布

问题:

I am starting to use node.js and I have a REST service that returns some data that I need to show in a page that's running on Apache, but I can retrieve that data in my application.

Here's the code of my REST service which is working fine:

server.js

var express = require('express'),
wine = require('./routes/wines');

var app = express();

app.configure(function () {
 app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
 app.use(express.bodyParser());
});

app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);

app.listen(3000);
console.log('Listening on port 3000...');

wine.js

var mongo = require('mongodb');

var Server = mongo.Server,
        Db = mongo.Db,
        BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('winedb', server);

db.open(function(err, db) {
    if (!err) {
        console.log("Connected to 'winedb' database");
        db.collection('wines', {strict: true}, function(err, collection) {
            if (err) {
                console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('wines', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.insert(wine, {safe: true}, function(err, result) {
            if (err) {
                res.send({'error': 'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    console.log('Updating wine: ' + id);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.update({'_id': new BSON.ObjectID(id)}, wine, {safe: true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error': 'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
}

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
            if (err) {
                res.send({'error': 'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
}
};

Here is my application running on apache, this is not working:

<!DOCTYPE html>
            <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
                <head>
                    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
                    <script type="text/javascript" src="jquery.min.js"></script>
                    <script type="text/javascript">
                        $(document).ready(function() {
                            $.ajax({
                                type: "GET",
                                data: '{}',
                                contentType: "application/json; charset=utf-8",
                                url: "myrestservice:3000/wines/",
                                dataType: "jsonp",
                                processdata: true,
                                success: function(data) {
                                    $('#wines').html(data);
                                }
                            });

                        });


                </script>
            </head>
            <body>
                <div id="wines"></div>
            </body>
        </html>

回答1:

Try res.jsonp() instead of res.send().