node.js - express怎么接收前端ajax请求?
大家讲道理
大家讲道理 2017-04-17 16:00:33
0
3
469

1.前端:

  $.ajax({
        type: "post",
        url: 'back.js',
        data: "123",
        success: sssqRverOnSuccess
    });
    
    function sssqRverOnSuccess(data) {
    console.log(data);
}

2.后端:

app.post('/back.js', function(err, req, res, next) {
    res.end('123');
});

3.back.js的内容

收到请求

4.浏览器控制台:
POST http://localhost:3000/back.js 404 (Not Found)

5.服务端控制台
POST /back.js 404 32.698 ms - 1257

问题:
1.为什么我用get请求可以成功,也就是浏览器控制台输出 “收到请求”。而post不能?

2.url只是一个标识,文件可以不存在(我昨天提的问题里告诉我的https://segmentfault.com/q/10...)。但是为什么会返回我的back.js的内容呢?难道xmlhttprequest和jquery ajax的url代表不一样?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
PHPzhong

You can try it

ajax({
    type:post,
    url:"/back.js"
    success:function(data){console.log(data)}
})

app.post('/back.js', function(req, res, next) {
    res.send('123');
});

My previous servers were all written like this

左手右手慢动作

Brother, your express is not running, don’t be misled by PHP. After nodejs is running, it can be understood as a combination of Apache and PHP. The back.js you visited is just a static file. Although nodejs can also be configured as an fcgi script to respond to content, that is a roundabout and unscientific approach! It is recommended that you follow the express introductory tutorial to understand the concepts of APP and routing!

迷茫

I wrote a paragraph when I was studying, but now that I use koa, express has forgotten it
req.body is what comes in from the post

router.post('/doCreate', function(req, res, next) {
    var data = new article.articleModel({
        name : req.body.name,
        cat : req.body.cat,
        author : req.body.author,
        time : moment(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
        desc : req.body.desc,
        content : req.body.content
    });

    data.save(function (err, doc) {
      if (err) {
        console.log(err);
        res.redirect('/article/fail');
      } else {
        console.log(doc + '数据保存成功');
        res.redirect('/admin/article/list');
      }
    });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template