Express+mongoose创建接口(api、跨域问题)
发布日期:2021-05-07 19:30:12 浏览次数:16 分类:原创文章

本文共 1721 字,大约阅读时间需要 5 分钟。

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

// 测试apivar 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();});

 

 

上一篇:解决谷歌浏览器http链接自动跳转到https的问题
下一篇:路径url

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月05日 14时57分18秒