【问题标题】:How can I run a node script in a Vite React project如何在 Vite React 项目中运行节点脚本
【发布时间】:2022-07-06 23:23:58
【问题描述】:

我正在尝试构建一个小 SPA,用户可以在其中运行 Presto 查询,我正在使用 Node presto 客户端。通过节点运行脚本时,它可以正常工作。我现在正在尝试通过 Vite 实现它

// lib/presto.js

import {Client} from 'presto-client'

const client = new Client({
  host: 'lga-xxx-adhoc.xxx.com',
  ssl: {
    rejectUnauthorized: true,
  },
  ...

  function getPrestoData(query) {
  return new Promise((resolve, reject) => {
    client.execute({ ...

这就是我目前的设置方式。当像这样通过 React FE 运行脚本时..

// App.jsx
import {getPrestoData} from './lib/presto'

function App() {
  const [data, setData] = useState([])

  const getData = async () => {
    await getPrestoData(query)
      .then(data => setData(data))
      .catch(error => console.log(error))
  }
  ...

我在浏览器中遇到错误,就像index.js:4 Uncaught ReferenceError: __dirname is not defined

我的package.json 中有"type": "module",,但我也尝试了以下var presto = require('presto-client');,但在浏览器中我需要的没有定义。

因此,是否可以像这样运行节点脚本,如果可以,如何运行。这就是我的src 文件夹的样子

├── src
│   ├── App.jsx
│   ├── favicon.svg
│   ├── index.css
│   ├── lib
│   │   └── presto.js
│   ├── logo.svg
│   └── main.jsx
├── tailwind.config.js
└── vite.config.js

【问题讨论】:

  • 你想在浏览器中运行一些节点脚本吗?

标签: javascript node.js reactjs presto vite


【解决方案1】:

api/run-presto-queryVite 是一个前端工具包,它不执行后端代码,因为你必须向后端发送请求

// App.jsx
function App() {
  const [data, setData] = useState([])

  const getData = async () => {
    const response = await fetch('http://mywebsite.com/api/run-presto-query', {
        method: "POST",
        body: // Your query here
    });
    setData(await response.json()); // Assuming you return results in a JSON format
  }

然后在您的后端,您将使用一个简短的(未经测试的)expressJS 示例配置一个指向将执行查询的类/函数的 API 路由。

// server.js

const express = require('express');
const app = express();
const port = 80;

const Presto = require('./lib/presto');

app.post('/api/run-presto-query', (req, res) => {
  res.send(Presto.getPrestoData(req.body.query)); // get the query parameter from the POST body, pass it to the presto client and return its results to the client
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2022-01-21
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    相关资源
    最近更新 更多