nodejs + express怎么实现Ajax方式及其简单功能。
发布于 11 年前 作者 gelihai 64876 次浏览 最后一次编辑是 8 年前

刚刚学nodejs,想用ajax实现登录的功能,实在没什么概念。 前端代码

$(function(){
		$("#submit").click(function(){
			var params ={
    			username: $("#username").val(),
    			password: $("#password").val()
    		};
    		$.ajax({
    			data: params,
    			url: 'http://127.0.0.1:3000/',
    			dataType: 'json',
    			cache: false,
    			timeout: 5000,
    			success: function(data){
    				var data = $.parseJSON(data);
    				alert(data.message);
    			},
    			error: function(jqXHR, textStatus, errorThrown){
    				alert('error ' + textStatus + " " + errorThrown);  
    			}
    		});
		});
		
	});

后端要怎么写呢?我只想做后端获得数据就行了。

module.exports = function(app){
app.get('/',function(req,res){
	console.log(req.body['username']);
	res.render('index',{
		title: 'ajax'
	});
});
}

获得的却是undefine,且路径都发生了变化。 刚刚学习nodejs,求指教

10 回复

我昨天问的同样的问题,后端是,res.json({“data”:“1”});括号内是你想要传的json数据。我前端用的$。post()

我按照你的方法加上去了,但是还是不行。我需要一个demo。。。谢谢

前端修改

$.ajax({
	......
	url: '/login',
	type:'post',
	......
})

后端增加

app.post('/login',function(req,res){
	if(req.body.username=='...'&&req.body.password=='...'){
		res.json({success:1});
	}
});

@alvis 问个问题,为什么不加res.end()

有兴趣的话看看angularjs

提供一个我React里面的一个例子: componentDidMount: function() { //ajax请求 var xmlhttp; if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }else if(window.ActiveXObject) { xmlhttp = new ActiveXObject(‘Microsoft.XMLHTTP’); }else { alert(‘必须提高浏览器版本才能浏览!’); return false; } //回调 xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4) { if(xmlhttp.status == 304 || (xmlhttp.status >= 200 && xmlhttp.status < 300)) { var renderMessage = JSON.parse(xmlhttp.responseText); if(this.isMounted()){ this.setState({ data: renderMessage, }); } } } }.bind(this); //请求 xmlhttp.open(‘post’,’/photo.list.server’,true); xmlhttp.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded;charset=utf-8”); xmlhttp.send(null); } 以上是前端的代码。

后台其实逻辑如下: var mongoose = require(‘mongoose’); var PhotoList = mongoose.model(‘PhotoList’); module.exports = function(req, res, next) { PhotoList.find({}, function(err, docs) { if(err) { res.end(‘Error’); return next(); } res.send(JSON.stringify(docs)); }); }

楼主用的什么浏览器?

body-parser安了么

回到顶部