我制作了一个简单的Backbone应用程序,我正在尝试使用带有Express服务器的MYSQL数据库中的JSON数据。 当我发送一个带有Express的GET请求向Backbone发送数据时,来自主干的html模板消失了,屏幕上只有JSON数组。如何在我的html /下划线模板中获取数据?
server.js(Express)
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var connection = mysql.createConnection({
host: 'localhost',
user: '***',
password: '***',
database: '***'
});
connection.connect();
app.get('/users', function(req, res) {
connection.query('SELECT * FROM users', function(err, result) {
if (err) {
console.error(err);
return;
}
res.json(result);
});
});
app.get('/users/:id', function(req, res) {
connection.query('SELECT * FROM users WHERE id =' + connection.escape(req.params.id), function(err, result) {
if (err) {
console.error(err);
return;
}
res.json(result);
});
});
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(8080);
app.js(Backbone)
var User = Backbone.Model.extend({
default: {
id: 0,
name: 'UserName',
age: 0
}
})
var Users = Backbone.Collection.extend({
model: User,
url: '/users'
})
var UserView = Backbone.View.extend({
template: _.template($('#UserViewTemplate').html()),
tagName: 'li',
render: function() {
this.el.innerHTML = this.template(this.model.toJSON())
return this;
}
});
var UsersView = Backbone.View.extend({
template: _.template($('#UsersViewTemplate').html()),
tagName: 'ul',
render: function() {
this.el.innerHTML = this.template(this.collection);
this.collection.each(function(user) {
var userView = new UserView({
model: user
});
this.$el.append(userView.render().el);
}, this)
return this;
}
});
var UserRouter = Backbone.Router.extend({
routes: {
'users': 'list'
},
list: function() {
console.log('list function called')
var usersView = new UsersView({
collection: users
})
$('body').append(usersView.render().el);
}
})
var users = new Users();
users.fetch().then(function() {
var router = new UserRouter();
Backbone.history.start({pushState: true});
});
答案 0 :(得分:0)
修正了它!我只需要使用路径 localhost:3000 /#users ,而不是localhost:3000 / users。