斗士狗
2016-06-18 08:57
采纳率: 0%
浏览 112

使用Node.js的Ajax请求

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?

图片转代码服务由CSDN问答提供 功能建议

                    

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

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

我看到的一种方法是这段代码:

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

 

我得到了错误:

  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
  

 

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_33724046 2016-06-18 09:10

    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.

    点赞 评论
  • perhaps? 2016-06-18 09:56

    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

    点赞 评论

相关推荐 更多相似问题