node服務配置,express配置引入vue項目中(前後端聯調)

1、使用express插件快速搭建node服務,首先安裝express插件

npm install express --save

通過express配置服務後,每次都需要node server.js顯得有些繁瑣,因此有了需求,能不能將自己配置的服務放在vue配置文件中,這樣只需要啓動vue項目,後臺配置也就完成了,答案是可以的。

先說總體過程,再說詳細內容

2、使用vue-cli3腳手架工具搭建的vue項目,在根目錄下新建vue.config.js配置文件,由於數據交互存在跨域問題,所以在項目中需要配置跨域,我們的後端服務配置在8100端口,前端端口配置在8080端口。跨域配置如下:

module.exports={
  devServer: {
    port: 8080,
    proxy: {
        '/api': {
            target: 'http://localhost:8100',
            changeOrigin: true,
            ws: true,
            pathRewrite: {
              '^/api': ''
            }
        }
    },
  },
}

配置好跨域後,在module.exports同級下配置後端服務。配置前先安裝body-parser插件,方法爲

npm install body-parser --save

該插件的作用就是方便提取post方式提交的數據,使用req.body就能獲得post提交的數據。如果不使用該插件將會變得很麻煩,建議安裝使用。

我是使用了mongdb數據庫,所以配置內容較多。

//後端提交數據配置
const express = require("express")
//引入mongoose庫
const mongoose = require("mongoose")
const DB_URL = "mongodb://127.0.0.1:27017/blog"
const bodyparser=require("body-parser")
mongoose.connect(DB_URL)
mongoose.connection.on("open", function() {
    console.log("鏈接成功");
})
//定義文檔模型,類似於數據庫建表
const User = mongoose.model(
    "userName",
    new mongoose.Schema({
        title: { type: String, require: true },
        body: { type: Number, require: true }
    })
)
//新增數據
User.create(
    {
        title: "喵星人",
        body: 19
    },
    function(err, doc) {
        if (!err) {
            console.log(doc);
        } else {
            console.log(err);
        }
    }
)
//刪除數據
User.remove({ age: 20 }, function(err, doc) {
    console.log(doc);
})
//修改數據
User.update({ name: "功夫熊貓1" }, { $set: { age: 28 } }, function(err, doc) {
    console.log(doc);
})
//新建app
const app = express();
//body-parser爲中間件,方便獲取post操作數據,需要先使用一下。
app.use(bodyparser.urlencoded({extended:false}))
//請求數據
app.get("/", function(req, res) {
    res.send("<h1>hello world</h1>");
})
app.post(`/dataName.html`, function(req, res) {
    if(req.body.user=='admin'&&req.body.password=='123'){
		res.sendFile(`${__dirname}/test.html`);
	}else{
		res.send("404");
	}
})
app.get("/dataName.html", function(req, res) {
    res.send("您好")
})
app.get("/home.html", function(req, res) {
  console.log(req.query);
})
//返回json類型數據
app.get("/data", function(req, res) {
    User.find({}, function(err, doc) {
        res.json(doc);
    });
})

//監聽8100端口
app.listen("8100", function() {
    console.log("8100");
})

配置完成後,只需要像以往啓動項目一樣,不同的是啓動項目同時,也啓動了node服務,當點擊提交數據時候,就會跳轉到響應內容中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章