vue 使用 node.js 本地服务器

1. 创建本地服务器

const express  = require('express')
const  multer =require('multer')
const   router =express.Router();

router.post('/upload',multer({
   //设置文件存储
    dest:'public/img',
}).array('file',1),function(req,res,next){
   let files = req.files;
   let file = files[0];
   let fileInfo = {};
   let path = 'public/img/' + Date.now().toString() + '_' + file.originalname;
   fs.renameSync('./public/img/' + file.filename, path);
   //获取文件基本信息
   fileInfo.type = file.mimetype;
   fileInfo.name = file.originalname;
   fileInfo.size = file.size;
   fileInfo.path = path;
   res.json({
     code: 0,
     msg: 'OK',
     data: fileInfo
   })
})


// const upload = multer({dest:'uploads/'})
const app = express();

app.listen(3000, () => {

    console.log(`端口:localhost:3000`)

})
  //设置跨域
app.all("*", function (req, res) {   //此时的 '*' 指用来处理所有的请求,从而在服务器端解决跨域的问题;
   res.header('Access-Control-Allow-Origin', '*');   //此时表示:允许 'http://127.0.0.1:5500' 地址来访问服务器;   
   res.header('Access-Control-Allow-Methods', 'GET,POST,PUT');           //此时表示:允许发的请求方式,如:'GET,POST,PUT';
   res.header('Access-Control-Allow-Headers', 'Content-Type');           //此时表示:允许发的请求头,如:'Content-Type' 请求头的类型;
   req.next();   //请求回来,并进行下一步的操作;
 });




app.get('/list',(req,res)=>{
   let r = [
      { id: 1,
         name: 'zs',
         imgurl:'usernames11',
         address:'重庆市潼南区xxxxxxx'},
         
         {   
            id: 2,
            name: '明明',
            imgurl:'imgUrlone',
            address:'重庆市梓潼区xxxxxxx'
          },
          {   
            id: 3,
            name: '小花',
            imgurl:'imgUrltwo',
            address:'重庆市铜梁区xxxxxxx'
          },
          {   
            id: 4,
            name: '阿大',
            imgurl:'imgUrlthree',
            address:'重庆市九龙坡区xxxxxxx'
          }
   ];
    let data = JSON.stringify(r);   // 服务器给浏览器的一般都是字符串,因此需要先将其转成 json 字符串;

    res.writeHead(200, {  // 可以用 writeHead(响应头) 设置当前的状态码为:200(成功);  并将传递的内容类型发过去(如: 'Content-type': 'application/json' 表示传递内容的是 json 字符串); 
      'Content-type': 'application/json'
    })
   
    res.write(data); // 此时的显示结果为:'{"id":1,"name":"zs"}',就是想要传递的 json 数据; (即:成功);
    res.end();
  });

app.get('/login',(req,res)=>{
   res.send({
      "code":200,
      "message":'登录成功',
      "data":{
           "name":'user.name1',
           "names":'user.name2',
      }
   })
})
app.get('/user',(req,res)=>{
   res.send({
      "code":204,
      "message":'用户信息',
      "data":{
           "age":'18',
            "email":'2932200044554@qq.com'
      }
   })
})

2. 在vue 项目配置本地路径 vue.config

const { defineConfig } = require('@vue/cli-service')
module.exports ={
  devServer:{
      '/api':{
        target: 'http://127.0.0.1:3000/',
        ws:true,
        changeOrigin:true,
        pathRewrite:{
              '^/api':'http://127.0.0.1:3000/',
        }
      }
     }
}

3. 在项目单页面配置  axios 请求接口

<template>
    <div>
    <button @click="btn">点击</button>
    </div>
</template>

<script>
export default{
  data(){
    return{

    }
  },
  methods:{
    btn(){
     let  url='http://127.0.0.1:3000/list'
      this.axios.get(url).then(res=>{
          console.log(res)
      })
    }
  },
 
}
</script>

<style scoped>



</style>

4.  在浏览器查看数据

 5.  后面会改进 从数据库拿到数据渲染到页面  先这样吧   先走通流程

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值