如何使用ExpressJS从jQuery ajax发布数据

时间:2015-06-02 04:23:51

标签: javascript jquery ajax node.js express

嗨所以我发送了一个jquery帖子数据:

<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
<script>
var form = document.getElementById('form');
form.noValidate = true;
form.addEventListener('submit',function(readURL){
    if(!event.target.checkValidity()){
        event.preventDefault();
        alert('please fill the form');
    }
},false);
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result);


            };

            reader.readAsDataURL(input.files[0]);
        }
    }

</script>

</head>
<body>
<form enctype="multipart/form-data" id="form" action="login.php" method="POST">
  <input name="image" type='file' required id="image" onchange="readURL(this);" accept="image/*" capture="camera" /><br/><br/>
  <img id="blah" src="#" alt="your image" /><br/><br/>


  <input type="submit" value="Upload"/>
    </form>
</body>

这是我的快递员:

                 $.ajax({
                    type: "POST",
                    url: app.config.backend_2 + '/notifications/usernames',
                    data: data,
                    contentType: 'application/javascript',
                    dataType: 'json',
                    success: function (result) {
                        console.log(result);
                    }
                });

如何从ajax获取数据以将其记录在 exports.save_usernames_for_notifications = function (req, res, next) { var start = function () { console.log(req); }; start(); }; 函数中?

1 个答案:

答案 0 :(得分:0)

您的expressjs应用程序中需要一个正文解析器中间件来解析您的JSON请求对象

https://www.npmjs.com/package/body-parser

要进行配置,您需要此代码

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST

然后在快递应用程序中获取数据只需执行此操作

console.log(req.body.data)