导入npm模块后无法编译反应网页

问题描述 投票:0回答:2

我有一个带有按钮的网页,该网页是用react构建的。我想在单击按钮时执行一些js代码。我要执行的代码是我制作的一个npm模块,它需要'pg'和'fs',并将处理与psql服务器的通信。当我在代码中添加“ const database = require('../ datadb / datadb.js')”(第2行)时,react无法编译。以下是我的按钮的代码。

import React, { Component } from "react";
const database = require('../datadb/datadb.js'); //HERE is the line that causes compilation failure

/* 
A function that handles when the LoadData button is clicked. This will allow for the data to be loaded in and stored into a database that can then be referenced.
*/
function Data() {
  alert("'The data is loading'"); //Creates a pop up box
  //HERE is where I will want to execute my modules code
}

/*
This function creates a component for the buttons. 
*/
class LoadData extends Component {
  render() {
    return (
      <div className="App">
        <button onClick={Data}>Load Data</button>
        <button>Open</button>
        <button>Save</button>
      </div>
    );
  }
}
export default LoadData;

哪个给出错误消息:

Failed to compile.

./src/datadb/node_modules/semver/semver.browser.js
  Line 1180:37:  'define' is not defined  no-undef
  Line 1181:3:   'define' is not defined  no-undef
  Line 1185:35:  'define' is not defined  no-undef
  Line 1186:3:   'semver' is not defined  no-undef

我已经自行测试了datadb模块,并且该模块正常工作。网页加载正确,按钮正常工作(如警报在第10行正常工作)

我对像React和JavaScript这样的与网页相关的代码非常陌生(我的大部分经验是Java和C),并已交给该项目来实现我的代码,但是我没有制作网页或按钮,所以我对反应非常不熟悉。 npm模块是否不可导出以作出反应?

这里是所请求的datadb.js文件

var fs = require('fs')
const {Client} = require('pg')






/**Connects to the client, then inserts all of the data from the given data array
 * 
 * @param {*} dataArray the data to insert
 * @param {*} client the DB client to connect to
 */
var insertRawData = async function(dataArray) {

    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })
    try {
        await client.connect()
        await client.query("BEGIN")

        var length = dataArray.length;
        for(let i = 0; i < length; i++) {
            queryString = "INSERT INTO rawdata.rawtable VALUES ( " + dataArray[i][0] + ", '" + dataArray[i][1] + "', " + dataArray[i][2] + ", " + dataArray[i][3] + ", " + dataArray[i][4] + ", " + dataArray[i][5] + ", " + dataArray[i][6] + ", " + dataArray[i][7] + ", " + dataArray[i][8] + ", " + dataArray[i][9] + ", " + dataArray[i][10] + ")" ;
            await client.query(queryString)
            console.log("NEW ROW INSERTED: " + queryString);
        }
        await client.query("COMMIT")

    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
}


/** 
 * Deletes all of the entries in the rawdata.rawtable table
 */
var deleteAllData = async function() {

    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    try {
        await client.connect()
        await client.query("DELETE FROM rawdata.rawtable WHERE year=1 OR year!=1")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
}


/** 
 * Returns the entire database
 */
var getAllData = async function () {
    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    var data;
    try {
        await client.connect()
        data = await client.query("SELECT * FROM rawdata.rawtable")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
    return data;
}

/** takes raw data returned from a SELECT psql query as input, returns the data 
 * in a 2d array format
 * 
 * @param {*} data the raw data returned from a query
 * @returns {*} the parsed data
 */
var parseDataFromQuery = async function(data){
    var returnValue = [];
    console.log("DATA: " + data.rows[0].year);

    var dataSize = data.rows.length;

    for(var i = 0; i < dataSize; i++){
        returnValue.push([data.rows[i].year, data.rows[i].month, data.rows[i].occupancy, data.rows[i].adr, data.rows[i].revpar, data.rows[i].supply, data.rows[i].demand, data.rows[i].revinue, data.rows[i].cprops, data.rows[i].crooms, data.rows[i].sparts]);
    }
    console.log(returnValue);
}



var selectTest = async function(){
    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    var data;
    try {
        await client.connect()
        data = await client.query("SELECT * FROM rawdata.rawtable WHERE year=9 AND month='Jan'")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }

    console.log(parseDataFromQuery(data, ['year']));
    //return data;
}



/**
 * Exports the functions to be used elsewhere
 */
module.exports = {
    insertRawData: insertRawData,
    deleteAllData: deleteAllData,
    getAllData: getAllData,
    selectTest: selectTest,
    parseDataFromQuery: parseDataFromQuery
};
javascript node.js reactjs web-site-project
2个回答
0
投票

因此,我们发现,您尝试在react前端应用程序中运行服务器端代码(使用PostgreSQL lib),这导致您的代码无法编译。

因此,我建议您查看这些链接,以了解如何使用Express和PostgreSQL创建NodeJS API服务器。

  1. [https://medium.com/@olinations/build-a-crud-template-using-react-bootstrap-express-postgres-9f84cc444438(ReactJS + Express + PostgreSQL)
  2. https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/(仅Express + PostgreSQL)
  3. https://kb.objectrocket.com/postgresql/nodejs-express-postgresql-tutorial-part-1-960(仅Express + PostgreSQL)

最后建议您看看Axios,这将有助于您调用API。

玩得开心!


-1
投票

此问题的一些可行解决方案。

  1. 请为模块使用import而不是require-尽管看起来一样,但是Webpack在编译代码时可能会以不同的方式对待动态导入和需求。
  2. 根据文件名判断,应该在服务器端(也称为Node.js服务)而不是客户端(在本例中为React Single Page Application)上执行。也许尝试在服务器端移动与数据库关联的逻辑,然后在此编译该逻辑?
© www.soinside.com 2019 - 2024. All rights reserved.