美文网首页
node+express连接远程服务器mongodb数据库

node+express连接远程服务器mongodb数据库

作者: 风中凌乱的男子 | 来源:发表于2020-09-10 11:38 被阅读0次

首先,用命令搭建express项目

express projectName
cd projectName
cnpm install

然后安装nodemon,mongoose

cnpm install nodemon 
cnpm install mongoose --save
启动项目 敲命令nodemon

启动成功


image.png

express项目根目录新建文件夹config,内建keys.js,敲如下代码

module.exports = {
    mongoURL: "mongodb://aoaoe:123456@it98k.cn/aoaoe" //参数不懂的私聊问我 v 1115009958
}

app.js 内添加如下代码


image.png
const mongoose = require("mongoose");
const db = require("./config/keys.js").mongoURL
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
    .then((res) => {
        console.log("远程数据库连接成功~~")
    }).catch((err) => {
        console.log(err)

    });

//express 设置允许跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,X-File-Name,authorization");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Cache-Control", "no-store");
    if (req.method == 'OPTIONS') {
        res.sendStatus(200).end();
    } else {
        next();
    }
});

打印出提示就是连接成功了


image.png

相关文章

网友评论

      本文标题:node+express连接远程服务器mongodb数据库

      本文链接:https://www.haomeiwen.com/subject/hpzuektx.html