Ajax发布数据从表单发送到express js body解析器

时间:2017-09-22 20:25:59

标签: html node.js ajax express body-parser

我想通过ajax发送表单数据到节点js,
我在节点js上使用带有体解析器的express 但是我在req.body

中未定义

我在网上搜索每一个并试了很多东西,没有什么对我有用 请帮助我正确地做到这一点。

| * | Html代码:

<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <title>Add</title>
</head>
<body>

    <h1>Welcome to Website </h1>
    <form id="addUserForm">
        <h3> Enter the your details : </h3>
        Name :<br><input type="text" name="nameView"><br><br>
        Email :<br><input type="email" name="mailView"><br><br>
        Mobile :<br><input type="number" name="mobileView"><br><br>
        <input type="submit" value="Submit">
    </form>

| * | Ajax代码:

    <script>
        $(document).ready( function()
        {
            $('#addUserForm').submit(function()
            {
                var formDataVar = new FormData($(this)[0]);

                console.log(formDataVar);
                $.ajax({
                    url: '/addUserFormSubmit',
                    type:'POST',
                    data: formDataVar,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                }).done(function(ResJryVar)
                {
                    console.log(ResJryVar);
                });
            })
        });

    </script>
</body>

</html>

| * |我也尝试过:

var formDataVar = new FormData();
formDataVar.append( 'nameView', input.files[0] );
formDataVar.append( 'mailView', input.files[1] );
formDataVar.append( 'mobileView', input.files[2] );

var formDataVar = {};
$.each($('#addUserForm').serializeArray(), function(i, field)
{
    formDataVar[field.name] = field.value;
});

| * |节点Js代码:

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.listen(8888,function()
{
    console.log("Server Started and Running ...");
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/',addUserFormFnc);
app.post('/addUserFormSubmit',addUserSubmitFnc);

function addUserFormFnc(req, res)
{
    res.sendFile('addUser.html', {root: __dirname });
}

function addUserSubmitFnc(req, res)
{
    console.log("Data Received : ");
    var userObjVar =
    {
        nameView: req.body.nameView,
        mailView: req.body.mailView,
        mobileView: req.body.mobileView
    };
    console.log(userObjVar);
    res.send(userObjVar);

}

3 个答案:

答案 0 :(得分:3)

正文解析器库不处理用multipart/form-data编码的数据。如果要发送该类型的数据,则应使用类似multer中间件的内容。

但在你的情况下,我认为你可以在不使用FormData界面的情况下逃脱。你可以这样重写你的浏览器代码:

const $form = $('#addUserForm')

$form.on('submit', submitHandler)

function submitHandler (e) {
  e.preventDefault()

  $.ajax({
    url: '/addUserFormSubmit',
    type:'POST',
    data: $form.serialize()
  }).done(response => {
    console.log(response)
  })
}

答案 1 :(得分:0)

 <html>
    <head>

       <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>
    </head>
    <body>     
    <form id="myForm" name="myForm">
                            <div>
                              <label for="comment">Comment:</label>
                              <textarea id="comment" name="comment"></textarea>
                            </div>
                           <div>
                              <label for="rating">Comment:</label>
                              <textarea id="rating" name="comment"></textarea>
                            </div>

                          <input type="submit" value="Submit!">
         </form>

        <script>

        $(document).ready(function () {
           $('form').submit(function (event) {
                        event.preventDefault();
                  //collect the form data using Id Selector what ever data you need to send to server
                        let comment=$('#comment').val();
                        let rating= $('#rating').val()

                        $.ajax({
                            url: 'replace your url',
                            data: JSON.stringify({"comment": comment, "rating": rating }),
                            processData: false,
                            type: 'POST',
                            contentType: 'application/json',
                            success: function (data) {
                                alert(data);
                            }
                        });


                    });
                })


    </script>
    </html>

答案 2 :(得分:0)

找到完整的代码: server.js

let express = require("express"),
multer = require('multer'),
crypto = require('crypto'),
fileExtension = require('file-extension'),
app = express();

let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, callback) {
crypto.pseudoRandomBytes(16, function (err, raw) {
callback(null, raw.toString('hex') + Date.now() + '.' + fileExtension(file.mimetype));
});


}
});

let upload = multer({ storage : storage}).single('image');

app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
// method to accept request from the file
app.post('/api/form-submit',function(req,res){

upload(req,res,function(err) {
console.log(req.body,'other form data---');
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});

app.listen(3000,function(){
console.log("App listening on port: 3000");
});

package.json

{
"name": "form_submit_using_ajax",
"version": "1.0.0",
"author": "Suraj Roy",
"keywords": "N/A",
"description": "N/A",
"dependencies": {
"express": "4.13.3",
"file-extension": "^4.0.5",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}

表格部分:

<form id="uploadForm" enctype="multipart/form-data" action="/api/form-submit" method="post">
<input id="file" type="file" name="image" />
<label>name :</label><input type="text" name="name" />
<input type="submit" value="Upload Image" name="submit">
<span id = "status"></span>
</form>

脚本部分

<script>
$(document).ready(function() {

$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},


success: function(response) {
$("#status").empty().text(response);
console.log(response);
}
});
//Code to disable the page refresh.
return false;
});
});
</script>