使用Node.js的Ajax请求


                    

环顾Google和堆栈溢出之后,我还没有找到一种将数据发布到我的Node.js服务器的方法。</ p>

我所见方法之间似乎存在差异,大概是由于折旧所致。</ p>

我看到的一种方法是这段代码:</ p>

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

app.use(express.bodyParser());

app.get('/ endpoint',function(req,res){
     var obj = {};
     obj.title ='标题';
     obj.data ='数据';

     console.log('params:'+ JSON.stringify(req.params));
     console.log('body:'+ JSON.stringify(req.body));
     console.log('query:'+ JSON.stringify(req.query));

     res.header('Content-type','application / json');
     res.header('Charset','utf8');
     res.send(req.query.callback +'('+ JSON.stringify(obj)+');');
});

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

我得到了错误:</ p>

  TypeError:express.createServer不是一个函数
     在对象上。<匿名>(c:\ Users \ Tobi \ Desktop \ ChangeLog \ ChangeLog \ app.js:2:19)
     在Module._compile(module.js:413:34)
     在Object.Module._extensions..js(module.js:422:10)
     在Module.load(module.js:357:32)
     在Function.Module._load(module.js:314:12)
     在Function.Module.runMain(module.js:447:10)
     在启动时(node.js:146:18)
     在node.js:404:3
</ code> </ pre>

我读了一些书,发现Express不再提供“中间件”了,它们需要单独包含-我也收到一条错误消息,说明如此。</ p>

对我的服务器实施Ajax Post请求的当前/最佳方法是什么?</ p>
     </ div>

展开原文

原文

After looking around google and stack overflow, I'm yet to find a way to post data to my Node.js server.

There seems to be disparity between the methods I've seen, presumably due to depreciation.

One method I saw was this code:

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

app.use(express.bodyParser());

app.get('/endpoint', function(req, res){
    var obj = {};
    obj.title = 'title';
    obj.data = 'data';

    console.log('params: ' + JSON.stringify(req.params));
    console.log('body: ' + JSON.stringify(req.body));
    console.log('query: ' + JSON.stringify(req.query));

    res.header('Content-type','application/json');
    res.header('Charset','utf8');
    res.send(req.query.callback + '('+ JSON.stringify(obj) + ');');
});

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

I get the error:

TypeError: express.createServer is not a function
    at Object.<anonymous> (c:\Users\Tobi\Desktop\ChangeLog\ChangeLog\app.js:2:19)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:146:18)
    at node.js:404:3

I did some reading and saw that Express had stopped coming with "middle-ware" and they would need to be included seperately - I also got an error message saying so.

What is the current / best way to implement Ajax Post requests to my server?

2个回答


由于您使用的是JSON,因此我将使用 json </ code>函数而不是 send </ code>,这样您的应用程序将以正确的内容类型发送响应并自动转换传递的内容 字符串到JSON对象。 body-parser </ code>还具有处理从客户端收到的JSON的功能。</ p>

下面是一些示例代码:</ p>

  var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/ endpoint',(req,res)=> {
     res.json({
         helloWorld:“世界你好!”,
         讯息:req.body.message
     });
});

app.listen(3000,()=> {
     console.log('服务器监听端口3000');
});
</ code> </ pre>

旧答案</ strong> </ p>

从Express 3开始,不推荐使用

createServer </ code>。您应该改用 express </ code>函数。</ p>

  var express = require('express');
var app = express();
</ code> </ pre>

修改</ strong> </ p>

@robertklep提到了不推荐的bodyparser。</ p>

您现在可以通过NPM将此中间件作为单独的模块获取</ p>

npm install body-parser </ code> </ p>

  var bodyParser = require('body-parser');
</ code> </ pre>

请访问此链接,以获取现在与express本身分离的中间件列表 </ p>
     </ div>

展开原文

原文

Since you're using JSON I would use the json function instead of send this way your app sends the response with the correct content-type and automatically converts the passed string to a JSON object. The body-parser also has a function to work with JSON received from the client.

Here's some example code:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/endpoint', (req, res) => {
    res.json({
        helloWorld: 'hello world!',
        msg: req.body.message
    });
});

app.listen(3000, () => {
    console.log('server listening at port 3000');
});

Old answer

createServer is deprecated since express 3. You should use the express function instead.

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

Edit

@robertklep mentioned the express bodyparser is also deprecated.

You can now get this middleware as a separated module via NPM

npm install body-parser

var bodyParser = require('body-parser');

Please visit this link for a list of middleware which are now separated from express itself.


以下是文档中有关如何正确定义路由的示例:表达</ a > </ p>

在不看示例的情况下阅读问题,听起来好像是对节点的实际请求失败了。</ p>

这是一个代码块,您可以从中开始并构建其他路由。 </ p>

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

  app.get('/',函数(req,res){
      res.send('Hello World!');
  });

  app.listen(3000,function(){
      console.log('示例应用程序在端口3000上监听!');
});
</ code> </ pre>

您可以使用浏览器或邮递员 </ p>之类的工具验证路由是否正常运行
     </ div>

展开原文

原文

Here is an example from the documentation about how to define routes correctly: express

Reading your question without looking the example it sounded like the actual request to node was failing.

Here is a code block you can start from and build additional routes.

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

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

 app.listen(3000, function () { 
     console.log('Example app listening on port 3000!'); 
});

You can verify routes are working correctly with a browser or a tool like postman

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐