[英]How can I run a node script in a Vite React project
I am trying to build a little SPA where a user can run a Presto query, I am using a Node presto client.我正在尝试构建一个小 SPA,用户可以在其中运行 Presto 查询,我正在使用 Node presto 客户端。 When running the script via node it works without any issues.通过节点运行脚本时,它可以正常工作。 I am trying to implement it now via Vite我现在正在尝试通过 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({ ...
This is how I currently have it set up.这就是我目前的设置方式。 When running the script via a React FE like so..当像这样通过 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))
}
...
I am getting an error in the browser like so index.js:4 Uncaught ReferenceError: __dirname is not defined
我在浏览器中遇到错误,例如index.js:4 Uncaught ReferenceError: __dirname is not defined
I have "type": "module",
in my package.json
but I have also tried the following var presto = require('presto-client');
我的package.json
中有"type": "module",
但我也尝试过以下var presto = require('presto-client');
but in the browser I get required is not defined.但在浏览器中我需要的没有定义。
Therefore is it possible to run a node script like this, and if so how.因此,是否可以运行这样的节点脚本,如果可以,如何运行。 This is how my src
folder is这就是我的src
文件夹的样子
├── src
│ ├── App.jsx
│ ├── favicon.svg
│ ├── index.css
│ ├── lib
│ │ └── presto.js
│ ├── logo.svg
│ └── main.jsx
├── tailwind.config.js
└── vite.config.js
Vite is a frontend toolkit, it does not execute backend code, for that you would have to send a request to your backend Vite 是一个前端工具包,它不执行后端代码,因为你必须向后端发送请求
// 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
}
then on your backend you'd have an API route configured that points to a class/function that will execute the query, using a short, (untested) expressJS example.然后在您的后端,您将使用一个简短的(未经测试的)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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.