简体   繁体   中英

Simple way of client-server communication in NodeJS

I found a very useful code snippet on GitHub that can provide simple server-client communication in NodeJS.

After some minor formatting, my code looks like this:

The client (Jade + Javascript)

head
    title jsonp test
    script(src='http://code.jquery.com/jquery-1.6.2.min.js')
    script(type='text/javascript').

    $(function () {
        $('#select_link').click(function (e) {
            e.preventDefault();
            console.log('select_link clicked');

            var data = {};
            data.title = "title";
            data.message = "message";
            $.ajax({
                type: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json',
                url: 'http://localhost:7776/domaintest',
                success: function (data) {
                    console.log('success');
                    console.log(JSON.stringify(data));
                }
            });
        });
    });

body
    #select_div
        a#select_link(href='#') Test

The server (Javascript)

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

app.use(express.bodyParser());

app.post('/domaintest', function(req, res){
    var obj = {};
    console.log('body: ' + JSON.stringify(req.body));
    res.send(req.body);
});

app.listen(7776);

Route defined to the client (I was told it's unnecessary for the server as app.post serves the purpose)

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    res.render('index');
});

module.exports = router;

The result is a simple text reading "Test" that can be clickable. When I click, the actual events should happen as far as I read it out from the code, but insted browser says POST http://localhost:7776/domaintest 404 (Not Found) in jquery-1.6.2.min.js:18 . To be very precise, the error occures in $.ajax , according to the debugger.

Since the jQuery code is practically unreadable because of the formatting (not judging, it might have its reason), I need your help. What's the possible source of the error? Did I forget mentioning something?

Change your server.js file to this. I havent tested the code but this should work.

    var express = require('express');
        var app = express.createServer();
        var router = express.Router();

        app.use(express.bodyParser());


    router.post('/domaintest', function(req, res, next) {
      var obj = {};
            console.log('body: ' + JSON.stringify(req.body));
            res.send(req.body);
    });

app.listen(7776);

You can read this for more information http://adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/

I think this is because your calling body-parser incorrectly. Body parser isn't part of express so you can't do express.bodyParser .

You need to include it like so:

var bodyParser = require('body-parser);
app.use(bodyParser.urlencoded({ extended: false }))

After some research and outside help, I've found the solution.

For domaintest , there was a route defined, which is almost identical to the one I defined for the client. Well, to the domaintest route, I had to add the next function call, right after router.get :

router.post('/', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({data: 'asd'}));
});

The so-called server code above is practically unused and unnecessary; domaintest serves as a server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM