res.send(返回前台的数据);或res.json(返回前台的数据);
item.js
var mongoose = require("mongoose");
// 连接数据库
mongoose.connect("mongodb://127.0.0.1/todo_list");
mongoose.connection.once("open", function() {
console.log("连接数据库成功~~")
})
mongoose.connection.once("close", function() {
console.log("连接数据库断开~~")
})
var Schema = mongoose.Schema;
var itemSchema = new Schema({
title: String,
status: {
type: Number,
default: 1
}, //0 删除;1 未完成;2 完成
userId: Schema.Types.ObjectId
})
var itemModuel = mongoose.model("item", itemSchema);
module.exports = itemModuel;
app.js
// 测试api
var itemModule = require("./models/item");
app.get("/testAPI", function(req, res) {
itemModule.find({},function(err, docs) {
if(!err) {
// console.log(docs)
// res.send(返回前台的数据);或res.json(返回前台的数据);
res.json(docs);
console.log("测试api成功")
}
})
})
页面请求:
$(function () {
$.ajax({
url: "http://localhost:3000/testAPI",
type: "get",
success: function (data) {
// 返回的是JSON对象,需要序列化成JSON字符串
$("#data").append(JSON.stringify(data));
},
error: function (err) {
$("#data").append("请求数据失败");
},
dataType: "json"
});
})
跨域报错:
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});