Ich habe versucht, AJAX Post-Anfrage mit JQuery zu meinem Node.JS Server in Node.JS und Express, aber es funktioniert nicht!JQuery Ajax Post Anfrage mit node.js und express
var express = require('express')
var app = express();
app.listen(8888);
app.configure(function(){
app.use(express.bodyParser());
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(app.router);
});
app.get('/', function (req, res){
res.render('ajax.ejs');
});
app.post('/ajax', express.bodyParser(), function (req, res){
console.log(req);
console.log('req received');
res.redirect('/');
});
Und das ist die ajax.ejs
:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$('#enter').click(function(){
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: { field1: 1, field2: 2 },
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
})
});
</script>
</head>
<body>
<form>
<input type="button" id="enter" value="Enter">
</form>
</body>
</html>
Wenn die ajax.ejs
geladen wird, es keine Ausgabe in der Konsole ist, so wird die Post-Anforderung hat nicht funktioniert. Was kann ich tun?
Vielen Dank!
move express.bodyParser() an die app.use() Abschnitt: app.use (express.bodyParser ()); Der Körper des Beitrags, den Sie über req.body abrufen können. – asgoth
Fertig! Also ändere ich 'console.log (req);' in 'console.log (req.body);'. Aber die Post-Anfrage funktioniert immer noch nicht, ich habe keine Ausgabe in der Konsole. – MrMangado