NodeJS中客户端-服务器通信的简单方法 [英] Simple way of client-server communication in NodeJS
问题描述
我在GitHub上找到了一个非常有用的代码段 ,该代码段可在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:
客户端(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
服务器(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);
为客户端定义的路由(有人告诉我服务器不必要,因为 app.post
用于此目的)
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;
结果是可以单击的简单文本测试".单击时,实际事件应该发生在我从代码中读出的范围内,但是插入的浏览器在中显示
.准确地说,根据调试器,错误发生在 POST http://localhost:7776/domaintest 404(未找到)
jquery-1.6.2.min.js:18 $.ajax
中.
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.
由于jQuery的格式实际上是不可读的(不判断,可能是有原因的),因此,我需要您的帮助.错误的可能原因是什么?我忘了提什么吗?
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?
推荐答案
经过一番研究和外界帮助,我找到了解决方案.
After some research and outside help, I've found the solution.
对于 domaintest
,定义了一条路由,该路由与我为客户端定义的路由几乎相同.好吧,对于 domaintest
路由,我必须在 router.get
之后紧接着添加下一个函数调用:
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'}));
});
上面所谓的服务器代码实际上是未使用和不必要的; domaintest
充当服务器.
The so-called server code above is practically unused and unnecessary; domaintest
serves as a server.
这篇关于NodeJS中客户端-服务器通信的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!