vue+elementUI框架,nodejs+router搭建本地服務器,數據庫用mongoose,axios請求碰到的一些問題
阿新 • • 發佈:2019-03-20
export local expr 題記 ble his nature 監聽 r.js
在做這個項目練手時碰到的一些問題記錄一下,加深印象
服務器的目錄層級如下:
一、簡單的搭建一個服務器,如何劃分路由
1.在搭建好的後端服務器 app.js 中導入路由,代碼如下:
var express = require(‘express‘) // 導入路由 用戶 var user = require(‘./router/user.js‘) var app = express() app.use(express.static(‘public‘)) // 在路由配置前添加以下代碼 解決跨域問題 app.all(‘*‘, function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); next(); }); app.use(‘/user‘,user); //掛載路由,如果沒有路由,或者只有/ ,映射到index路由 app.listen(3000, () => { console.log(‘Server Running...‘) })
2.路由頁面 user.js 代碼如下:
var express = require(‘express‘); // 導入 mongoose 數據庫 var User = require(‘../mongoose/mongoose.js‘) var router = express.Router(); router.get(‘/register‘,function(req, res, next) { console.log(req) res.send(‘請求數據成功‘) }) module.exports= router;
二、如何引用數據庫
在上述步驟當中,在 user.js 內已經導入mongoose 數據庫,現在掛上數據庫 mongoose。js 文件代碼如下:
var mongoose = require("mongoose") // mongoose.connect(‘mongodb://數據庫的ip地址:端口號/數據庫名‘); mongoose.connect(‘mongodb://localhost:27017/txl‘) // 通過Schema來創建Model // Model代表的是數據庫中的集合(users),通過Model才能對數據庫進行操作 // mongoose.model(modelName,schema) (集合名,Schema) // modelName 就是要映射的集合名,mongoose會自動將集合名變成復數 var Schema = mongoose.Schema; // 定義一個user的Schema var UserSchema = new Schema({ username : { type: String }, // 用戶賬號 password: { type: String }, // 密碼 email: { type: Number }, // 郵箱 birthday : { type: Date }, // 出生年月 qq : { type: String }, // QQ tel: { type: String }, // 手機 gender : { type: String }, // 性別 signature : { type: String } // 個性簽名 }); // 監聽連接狀態 mongoose.connection.on(‘connected‘, function () { console.log(‘Mongoose connection open to ‘ + ‘mongodb://localhost:27017/txl...‘); }); mongoose.connection.on(‘error‘,function (err) { console.log(‘Mongoose connection error: ‘ + err + ‘...‘); }); mongoose.connection.on(‘disconnected‘, function () { console.log(‘Mongoose connection disconnected...‘); }); // 對上面的定義的user的schema生成一個User的model並導出 module.exports = mongoose.model(‘User‘,UserSchema);
三、前端頁面發送數據請求
1. npm i axios
2. 在 main.js 中插入如下代碼:
// axios 發送請求 import axios from ‘axios‘ Vue.prototype.$ajax = axios
3. 在所需頁面使用 axios 發送數據請求
this.$refs[formName].validate((valid) => { if (valid) { this.$ajax.get(‘/user/register‘, { data }).then((resData) => { console.log(resData) }) } else { return false } })
4.做好這些之後,會報錯
因為 vue 是 8080 的端口,而本地服務器是 3000 的端口,存在跨域問題,解決這個問題要在 vue項目 config 文件夾下的 index.js 文件內進行配置
找到 proxytable屬性,進行如下配置:
proxyTable: { ‘/‘:{ target:‘http://127.0.0.1:3000‘, changeOrigin: true } },
打開界面,發送請求顯示
則服務器代理成功
vue+elementUI框架,nodejs+router搭建本地服務器,數據庫用mongoose,axios請求碰到的一些問題