NodeJs 使用express在本地請求后台服務接口


express

  • 基於 Node.js 平台,快速、開放、極簡的 Web 開發框架
  • npm init -y
  • npm i express cors
  • 編寫 server.js 文件
    const mysql = require('mysql');
    const express = require('express');
    const cors = require('cors'); // 解決跨域
    const app = express();
    app.use(cors());
    const connection = mysql.createConnection({
    host : '172.16.101.222', // 數據庫ip
    user : 'name', // 數據庫用戶名
    password : 'mima', // 數據庫密碼
    database: 'dataBase' // 數據庫名稱
    });
    connection.connect();
    app.get('/server', (req, res) => {
    connection.query("SELECT * from med_alias_copy where alias='紫金'", function (error, results, fields) {
    if (error) throw error;
    console.log(results);
    res.status(200).json(results);
    });
    })

    // 前端項目訪問接口的地址
    const hostname = '127.0.0.1';
    const port = 9000;
    app.listen(port, hostname, () => {
    console.log(`❗❗❗ Server is running at http://${hostname}:${port}/`)
    })

    在Vue應用中使用

  • import axios from 'axios'
    const state = {
      products: []
    }
    const getters = {}
    const mutations = {
      setProducts(state, payload) {
        state.products = payload
      }
    }
    const actions = {
      async getProducts({ commit }) {
        try {
          const { data } = await axios({
            method: 'GET',
            url: 'http://127.0.0.1:3000/products'
          })
          commit('setProducts', data)
        } catch (err) {
          // eslint-disable-next-line no-undef
          $vue.$message.error(err.toString())
        }
      }
    }
    
    export default {
      namespaced: true,
      state,
      getters,
      actions,
      mutations
    }

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM