大家好我来自移动开发,并试图了解更多关于节点js运行时,所以我已经有一个简单的“应用程序”js客户端和我试图使用它与节点js表达服务器
为了我的目的,我使用了一个静态文件,因为我的所有html都是由js用DOM生成的。
问题:
当我正在使用ajax发布在数据库中存储值的帖子时,它总是将我重定向到index.html,并且不执行我的客户端回调代码来创建表。 < / p>
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) {
var 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 executeSql = require("../scripts/execute-sql");
router.get('/', function (req, res, next) {
executeSql.executeSelect(res, function (rows, fields) {
res.json(rows);
}, "SELECT * FROM `footTour-sgbd`.player;")
});
router.post('/submit-player', function (req, res, next) {
let obj = req.body;
let keys = Object.keys(obj);
let placeHolders = new Array(keys.length).fill("?");
let values = Object.keys(obj).map(key => obj[key]);
let sql = "INSERT INTO `footTour-sgbd`.`player` (" + keys.toString() + ") VALUES (" + placeHolders.toString() + ")";
sql = mysql.format(sql, values);
executeSql.executeSelect(res, function (rows, fields) {
// res.json(rows);
res.end('{"success" : "Updated Successfully", "status" : 200}');
}, sql);
});
module.exports = router;
js客户端请求:
let formPlayer = createForm(formName, formName);
formPlayer.addEventListener("submit", function (response) {
let playerName = document.getElementById("name").value;
let playerHeight = document.getElementById("height").value;
let playerBirthdate = document.getElementById("birthDate").value;
let playerCountry = document.getElementById("countryEnum").value;
let playerPosition = document.getElementById("positionTypeEnum").value;
// let player = formToJson(formPlayer);
let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
insertPlayer(
function (response) {
createPlayersTable();
}, function (status, response) {
showSnackBar(`Error creating player (${status})`, 3000);
createPlayersTable();
}, player);
});
function insertPlayer(onSuccess, onError, data) {
ajaxHelper("/players/submit-player", onSuccess, onError, "POST", data);
}
function ajaxHelper(url, onSuccess, onError, verb, data) {
verb = verb || "GET";
let xhr = new XMLHttpRequest();
xhr.open(verb, url);
xhr.responseType = "json";
xhr.addEventListener("load", function () {
if (this.status === 200) {
onSuccess && onSuccess(xhr.response);
} else {
onError && onError(this.status, xhr.response);
}
});
if (data) {
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
}
答案 0 :(得分:2)
尝试在EventListener:
形式中添加preventDefault()formPlayer.addEventListener("submit", function (evt) {
evt.preventDefault(); //<-- THIS
let playerName = document.getElementById("name").value;
let playerHeight = document.getElementById("height").value;
let playerBirthdate = document.getElementById("birthDate").value;
let playerCountry = document.getElementById("countryEnum").value;
let playerPosition = document.getElementById("positionTypeEnum").value;
// let player = formToJson(formPlayer);
let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
insertPlayer(
function (response) {
createPlayersTable();
}, function (status, response) {
showSnackBar(`Error creating player (${status})`, 3000);
createPlayersTable();
}, player);
});