サーバーをセットアップする
- 新しいプロジェクトが開きます
- 初期化
package.json
端末入力をnpm init
- エントランスファイル
server.js
私は著者に関するエントリー書類と書き込まれた情報を修正
- 現在のプロジェクトに必要なモジュールをインストールします
npm install express
- Expressを導入してアプリをインスタンス化する
const express = require('express')
const app = express()
const port = process.env.PORT || 5000
app.listen(port,()=>{
console.log(`server running on port ${port}`)
})
- ルートを設定する
app.get('/',(req,res)=>{
res.send('hello world')
})
入力端子は、node server.js
ページのルートパスが表示されますhello world
-
インストールは
nodemon
nodemon
、各変更の役割は、面倒なステップを避けるために再起動する必要がありますされる
sudo npm install nodemon -g
ことによりnodemon server.js
開始し -
変態
package.json
のscripts
// 前面通过 npm run start 线上打包启动
// 后面通过 npm run server 本地启动
"scripts":{
"start":"node server.js",
"server":"nodemon server.js"
}
以下は、サーバーが正常にポートを開始したことを証明するよう
です
データベースに接続する
mongoDBデータベースに接続するmongoDBデータベース
をインストールするhttps://blog.csdn.net/weixin_43883485/article/details/104534533
インストールを移動するmongoose
npm install mongoose
マングースの紹介
const mongoose = require("mongoose")
他にファイルのアドレス
新しいdb.js
におけるdb.js
アドレス名は、ローカルデータベースに書き込まれ
、このステップは、最初に作成する前にmongo
データベースtestDB
であればNavicat Premium
、新たなビジュアルインターフェイスによって可能に
して、ダブルクリックしてtestDB
データベースをオープンし、それを
ターミナルで新しいデータベースを作成しますtestDB
-mongodbを入力してサーバーを起動します
-mongoを入力してmongodbに接続します
show databases //显示当前所有数据库
use testDB //进入testDB数据库 如果没有testDB数据库 会创建testDB数据库
db //显示当前的数据库
次に、データベースのアドレスを入力して外部に公開します
module.exports = {
mongoURI:"mongodb://127.0.0.1/testDB"
}
戻るserver.js
紹介
const db = require("./db.js").mongoURI;
// 连接数据库
// mongoose.connect("mongodb://127.0.0.1/testDB",{useMongoClient:true})
mongoose.connect(db,{useMongoClient:true})
.then(()=>console.log('mongoDB is connected'))
.catch(err=>console.log(err))
端末が再起動しserver.js
、データベース接続の成功を見ることができますプロンプトが表示され
、データベース接続がに成功したときに、2つの警告の出現を
警告を解決します
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
以前の接続方法が新しいバージョンに適用されない可能性があります。
次のように変更してください
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.once('open',() => {
console.log("mongoDB is connected")
});
起動は正常です。
その後、インターフェースの作成を開始できます