• 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
      }
  • 相关阅读:
    bzoj1297 [SCOI2009]迷路
    bzoj1085 [SCOI2005]骑士精神
    bzoj1009 [HNOI2008]GT考试
    uoj#73 【WC2015】未来程序
    bzoj1016 [JSOI2008]最小生成树计数
    bzoj2818 Gcd
    python递归——汉诺塔
    python参数
    python函数
    为什么会出现__pycache__文件夹?
  • 原文地址:https://www.cnblogs.com/zhangyezi/p/13841512.html
Copyright © 2020-2023  润新知