Express+mongoose创建接口(api、跨域问题)

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();
});

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值