vue项目如何请求nodejs接口

Nodejs部分

搭建一个服务器写一个测试接口 (接口返回一个数据就行,不需要完全按我这样)
const express=require('express');
const path=require('path');
const app=express();
//模板配置
app.engine('art',require('express-art-template'));
app.set('views',path.join(__dirname,'views'));
app.set('view engine','art');

app.locals.users=[{
	name:"张三",
	age:20
},{
	name:"李四",
	age:30
}]

app.get('/index',(req,res)=>{
	res.render('index',{
		msg:'首页'
	})
})

app.get('/api/list',(req,res)=>{
	res.render('list',{
		msg:'列表页'
	})
})
//端口监听
app.listen(3000);

vue部分

用vue-cli创建一个项目
  //在router/index.js文件下创建组件的路由
  {
    path: '/user',
    name: 'User',
    component:()=>import('@/components/User.vue')
  }
//在components文件下创建组件我这里的请求进行了封装
<template>
  <div>
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>性别</th>
          <th>邮箱</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td>{{user.sex}}</td>
          <td>{{user.email}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { nodejs } from '../api/api';
export default {
  name: 'user',
  data () {
    return {
      data: '1',
      users: []
    }
  },
  methods:{
     getnodejs(){
      nodejs().then((res) => {
        this.list = res.list
      })
     }
  },
  created () {
     this.getnodejs();
  },
}
</script>

<style lang="less" scoped>
  .table{
    text-align: center;
    background-color: blanchedalmond
  }
</style>

前端跨域实现

//在项目根目录下的vue.config.js文件下
module.exports = {
    //前端跨域,这里的服务器是nodejs
    devServer: {
        hot: true,
        clientLogLevel: 'warning',
        port: 8080,
        proxy: {
            '/api': {
                target: 'http://localhost:3000/',
                ws: false,
                changeOrigin: true
            }
        }
    },
}

然后启动node.js写好的服务器和前端vue项目就可以了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值