Vue 和 Vite ,创建一个 Node.js 服务

618 阅读1分钟

在使用 Vue 和 Vite 时,你可以通过以下步骤创建一个 Node.js 服务,并在 Vue 文件中调用这个 Node.js 服务提供的接口

首先创建vue3+vite项目

npm create vite@latest
yarn create vite
pnpm create vite

npm yarn cnpm选择一个创建完成vite项目-----

cd my-project 
npm install 
npm run dev

1. 创建一个新的 Node.js 项目

首先,创建一个新的文件夹作为你的 Node.js 项目目录,并初始化一个新的 Node.js 项目:

mkdir my-node-server
cd my-node-server
npm init -y

2. 安装必要的依赖

安装 Express.js 和其他必要的依赖:

npm install express cors

3. 创建 Node.js 服务

创建一个简单的 Express.js 服务器,例如在 server.js 文件中:

const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 3001;

app.use(cors()); // 允许跨域请求

app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello from Node.js API!' });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

4. 在 Vue 中调用 Node.js 服务

使用 Axios 或其他 HTTP 客户端库,在 Vue 文件中调用 Node.js 服务提供的接口:

首先,确保你的 Vue 项目已经创建并运行。然后,在 Vue 组件或其他适当的位置使用 Axios(或其他 HTTP 客户端库)进行 HTTP 请求。

安装 Axios:

npm install axios

在 Vue 文件中:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <p>{{ message }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      message: '',
    };
  },
  methods: {
    async fetchData() {
      try {
        const response = await axios.get('http://localhost:3001/api/data');
        this.message = response.data.message;
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
  },
};
</script>

setup格式:

<script setup>
import { ref } from 'vue';
import axios from 'axios';
const message = ref('0');

async function fetchData() {
  try {
    const response = await axios.get('http://localhost:3001/api/data');
    message.value = response.data.message;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
</script>

<template>
  <h3>首页</h3>
  <button @click="fetchData">Fetch Data</button>
  <p>{{ message }}</p>
</template>

确保在 Vue 项目中运行时,Node.js 服务也在运行(使用 node server.js 命令)。然后,你应该能够点击按钮并从 Node.js 服务获取数据。

这样就成功调用node服务了