简体   繁体   English

将数据对象发送到NodeJs服务器时,Ajax失败

[英]Ajax fails when sending a data object to the NodeJs server

when pressing a button this code gets executed 当按下一个按钮时,该代码被执行

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this 服务器正在监听

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. 每当按下按钮时,“错误”就会记录在控制台中。 The Ajax call always fails. Ajax调用始终失败。

Even when writing res.send("Success"); 即使编写res.send("Success"); the client will log "Error". 客户端将记录“错误”。 What am I missing? 我想念什么?


Update: I installed the body parser middleware and use this code now 更新:我安装了主体解析器中间件并立即使用此代码

my app.js 我的app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

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

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route 我的路线

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function 和我的客户功能

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail() 并且在执行Ajax调用时,客户端仍然会遇到.fail()

You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. 您正在使用GET http方法,该方法不应包含正文,而应将数据附加到url的后面。 Or if you want to use a body, then switch to a POST. 或者,如果要使用主体,请切换到POST。

url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext

If you're using POST don't forget: 如果您使用的是POST,请不要忘记:

'Content-Type': 'application/json',

Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser: 编辑:在服务器上,您需要解析JSON请求,最好使用称为body-parser的中间件来完成:

npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());

This will parse your JSON and add it to req.body . 这将解析您的JSON并将其添加到req.body

Client request is : 客户要求是:

function submitData() {
        $.ajax({
            type: 'POST',
            url: '/questionnaire/submit', // listen to a route
            dataType: "json",
            data: {
                satisfactory: "house",
                improvement: "bla",
                rating: "this is a text"
            }
        }).done(function () {
            $(location).attr('href', '/sendOff'); // redirect to another route
        }).fail(function () {
            console.log("Error");
        });
    }

and the server is listening on this Using bodyParser middleware in your node backend : 并且服务器正在您的节点后端中侦听此Using bodyParser中间件:

app.post('/questionnaire/submit', function (req, res) {
    var data = req.body; // Get the data object from the Ajax call

    console.log(data);

    res.end(); // Send nothing back
});

Try this.. 尝试这个..

Client Side 客户端

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit', // listen to a route
        'Content-Type': 'application/json',
        data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
    }).done(function () {
        console.log('hi')
    }).fail(function () {
        console.log("Error");
    });
}

On server Side: 在服务器端:

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

var app = express();
app.use(bodyParser.json());

app.post('/questionnaire/submit', function (req, res) {
var data = req.body
    console.log(data);

    res.send(null); // Send nothing back
});

You have to install body-parser library using following command. 您必须使用以下命令安装body-parser库。

npm install --save body-parser npm install-保存正文解析器

It will log "Hi" as ajax done is called. 当ajax完成被调用时,它将记录“ Hi”。 BTW You have redirected the page to 'sendOff' in your question. 顺便说一句,您已将页面重定向到问题的“ sendOff”。 If you are not understanding anything plz comment below. 如果您不了解任何内容,请在下面评论。

You just have to replace 您只需要更换

dataType: "json",

with this: 有了这个:

'Content-Type': 'application/json'

in $.ajax request 在$ .ajax请求中

Hope this will work.. I have tried & tested. 希望这会工作..我已经尝试和测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM