节点js路由器没有处理删除

时间:2017-07-10 13:02:17

标签: javascript node.js ajax express

我的节点js路由器它没有处理删除方法但其他所有其他处理得很好(GET,POST,UPDATE等)但是删除没有到达路由器我可以&#39 ; t想为什么。

ajax它正确地执行了请求,至少它似乎正在这样做。

ajax请求:

function ajaxHelper(url, onSuccessArray, onErrorArray, onFinishArray, verb, data) {
    verb = verb || "GET";
    document.getElementById("loader").style.display = "block";
    let xhr = new XMLHttpRequest();
    xhr.open(verb, url);
    xhr.responseType = "json";
    xhr.addEventListener("load", function () {
        document.getElementById("loader").style.display = "none";
        let status = this.status;
        if (status === 200) {

            if (onSuccessArray) {

                onSuccessArray.reverse();
                onSuccessArray.forEach(function (onSuccess) {

                    onSuccess && onSuccess(xhr.response)
                });
            }
        } else {

            if (onErrorArray) {

                onErrorArray.reverse();
                onErrorArray.forEach(function (onErrorCallback) {

                    onErrorCallback && onErrorCallback(status, xhr.response);
                })
            }
        }
        if (onFinishArray) {

            onFinishArray.reverse();
            onFinishArray.forEach(function (onFinishCallback) {

                onFinishCallback && onFinishCallback(status);
            })
        }
    });
    if (data) {

        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.send(JSON.stringify(data));
    } else {

        xhr.send();
    }
}

function removePlayer(onSuccessArray, onErrorArray, onFinishArray, data) {

    ajaxHelper("/players/delete-player", onSuccessArray, onErrorArray, onFinishArray, "DELETE", data);
}

app.js

let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');

let index = require('./routes/index');
let cups = require('./routes/route-cup');
let leagues = require('./routes/route-league');
let players = require('./routes/route-player');
let teams = require('./routes/route-team');

let app = express();

app.use(favicon(path.join(__dirname, 'public', '/images/favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());


app.use('/cups', cups);
app.use('/leagues', leagues);
app.use('/players', players);
app.use('/teams', teams);
app.use(express.static("public", {
    "index": "index.html"
}));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

路由器:

let express = require('express');
let router = express.Router();
let mysql = require("mysql");
let sqlHelper = require("../scripts/sql-helper");

router.get('/', function (req, res, next) {
    let sqlQuery = "SELECT * FROM " + dbName + ".player;";
    sqlHelper.executeSql(res, sqlQuery, function (rows, fields) {

        res.json(rows);
    })
});

router.get('/free-players', function (req, res, next) {
    let sqlQuery = "SELECT * FROM " + dbName + ".player WHERE 'teamName' <> ''";
    sqlHelper.executeSql(res, sqlQuery, function (rows, fields) {

        res.json(rows);
    })
});

router.post('/submit-player', function (req, res, next) {
    let keys = objectHelper.getObjectKeys(req.body);
    let values = objectHelper.getObjectValues(req.body);
    let placeHolders = new Array(keys.length).fill("?");
    let sqlQuery = "INSERT INTO " + dbName + ".`player` (" + keys.toString() + ") VALUES (" + placeHolders.toString() + ")";

    sqlQuery = mysql.format(sqlQuery, values);
    sqlHelper.executeSql(res, sqlQuery, function (rows, fields) {

        res.json(rows);
    });
});

router.put('/update-player', function (req, res, next) {
    let keys = objectHelper.getObjectKeys(req.body);
    let values = objectHelper.getObjectValues(req.body);
    let sqlQuery = "UPDATE " + dbName + ".`player` SET ";
    let valuePair = [];
    keys.forEach(function (key, index) {
        if (values[index] !== null) {

            valuePair.push(key + "=" + "'" + values[index] + "'");
        } else {

            valuePair.push(key + "=" + values[index]);
        }
    });
    sqlQuery = sqlQuery + valuePair.toString() + " WHERE " + valuePair[0];
    sqlHelper.executeSql(res, sqlQuery, function (rows, fields) {

        res.json(rows);
    });
});

router.delete('/delete-player', function (req, res, next) {
    let sqlQuery = "DELETE " + dbName + ".`player` WHERE id=" + req.body;
    sqlHelper.executeSql(res, sqlQuery, function (rows, fields) {

        res.json(rows);
    });
});

module.exports = router;

服务器日志:

GET /players 304 53.636 ms - -
GET /teams 304 46.161 ms - -
GET /players 304 13.676 ms - -
DELETE /players/delete-player 400 3059.064 ms - 1397
Error: No default engine was specified and no extension was provided.

1 个答案:

答案 0 :(得分:2)

您收到400响应(“错误请求”),因为您最有可能向后端发送(JSON编码的)字符串

但是,使用application/json时,您发送的数据应该是(JSON编码的)对象或数组,而不是字符串。这就是服务器返回400的原因。

更典型的解决方案是在URL本身中将属性传递给删除:

DELETE /players/delete-player/jack

你会使用这样的路线:

router.delete('/delete-player/:name', ...)

并将该名称作为req.params.name(在此示例中等于“jack”)。

此处有关路线参数的更多信息:http://expressjs.com/en/guide/routing.html#route-parameters