【问题标题】:Connecting a postgresql database, node.js and react.js连接一个 postgresql 数据库,node.js 和 react.js
【发布时间】:2021-04-13 16:50:55
【问题描述】:

我创建了一个 node.js 文件:

const express = require("express");

const app = express();
const bodyParser = require("body-parser");
var dateFormat = require('dateformat');

app.set("port", 3001);

app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));

const Pool = require("pg").Pool;
const config = {
    host: "localhost",
    user: "Austin",
    password: "astros5",
    database: "cubing"
};

const pool = new Pool(config);

app.post("/add-time", async (req,res) => {
    const name = req.body.name;
    const time = req.body.time;

    
    const template = 'INSERT INTO times (name,time) VALUES ($1,$2)';
    const response = await pool.query(template, [name,time]);
    

});

app.get("/list", async (req,res) => {
    const template = await pool.query('SELECT * FROM times');
    res.json({times: template.rows});

})

app.get("/", (req,res) => {
    res.json({ message: "We did it!" });
});

app.listen(app.get("port"), () => {
    console.log('Server at: http://localhost:${app.get("port")}/');
});

这可以在我的本地计算机上打开一个数据库。现在,我想把它带到我用 react.js 构建的网页上。我有一个 util.js 文件:

require("isomorphic-fetch");

function addName(time) {
  return fetch('http://localhost:3001').then(function(resp)
    {
      return resp.json();
    });
}

function handleError(error) {
  console.warn(error);
  return null;
}

module.exports = {
  getInfo: function(time) {
    return addName(time).catch(handleError);
  }
};

在我的主 index.js 文件中,我添加了一个构造函数,this.state = {name:"..."};,两个方法:

  handleUpdate(evt) {
    this.setState({name: evt.target.value});
  }
  
  async handleAddName(evt) {
    const user = await getInfo(this.state.name);
    this.setState({user});
  }

现在在渲染下我有:

      <p><input type='text' value={this.state.name} onChange={this.handleUpdate.bind(this)} /></p>
      <button className='button-style' onClick={this.handleAddName.bind(this)}>Add Time</button>

当我在主页的文本框中输入任何内容然后单击按钮时,什么也没有发生。我正在尝试基于我们在我的一个课程中使用的文件来构建它,但是在那个课程中,我们只检索信息,我们没有发布任何内容。我正在运行我的文件 node server.jsnpm run dev

你知道我做错了什么吗?它不返回任何东西。

编辑:我在 http://localhost:3000 上运行 npm Edit1:我的 util.js 文件

require("isomorphic-fetch");

function addName(time) {
  return fetch('http://localhost:3001/add-time', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    data: JSON.stringify({name})
  }) 
}

function handleError(error) {
  console.warn(error);
  return null;
}

module.exports = {
  getInfo(name) {
    return addName(name).catch(handleError);
  }
};

【问题讨论】:

    标签: javascript node.js reactjs postgresql


    【解决方案1】:

    问题不止一个。我将发布更正后的代码并附上解释。

    // index.js (server)
    const express = require("express");
    const cors = require("cors")  // install cors
    const bodyParser = require("body-parser");
    var dateFormat = require('dateformat');
    
    const app = express();
    app.set("port", 3001);
    
    app.use(cors())
    app.use(bodyParser.json({ type: "application/json" }));
    app.use(bodyParser.urlencoded({ extended: true }));
    
    const Pool = require("pg").Pool;
    const config = {
        host: "localhost",
        user: "Austin",
        password: "astros5",
        database: "cubing"
    };
    
    const pool = new Pool(config);
    
    app.post("/add-time", async (req, res) => {
        const name = req.body.name;
        const time = req.body.time;
        // It would be better to set the time server-side
        const timeStamp = dateFormat(time, dateFormat.masks.isoDateTime)
    
        const template = 'INSERT INTO times(name, time) VALUES($1, $2)'
        const response = await pool.query(template, [name, timeStamp])
    
        res.end()
    });
    
    app.get("/list", async (req, res) => {
        const template = await pool.query('SELECT * FROM times');
        res.json({ times: template.rows });
    
    })
    
    app.get("/", (req, res) => {
        res.json({ message: "We did it!" });
    });
    
    app.listen(app.get("port"), () => {
        console.log(`Server at: http://localhost:${app.get("port")}/`);
    });
    
    // App.js (client)
    import React from 'react';
    import { addName } from "./utils";
    
    // I'm using hooks... That just avoids `this`
    function App() {
      const [name, setName] = React.useState("")
    
      function handleUpdate(evt) {
        setName(evt.target.value);
      }
    
      // I assume you want to add the name with a timestamp.
      // There were name and time names confused.
      async function handleAddName(evt) {
        await addName(name);
      }
    
      return <div>
        <p><input type='text' value={name} onChange={handleUpdate} /></p>
        <button className='button-style' onClick={handleAddName}>Add Name</button>
      </div>
    }
    
    export default App;
    
    // utils.js (client)
    import "isomorphic-fetch"
    
    export function addName(name) {
        // This is how to do a POST request. 
        // Note: Never trust your client. Better to set time on the server.
        return fetch('http://localhost:3001/add-time', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name, time: Date.now() })
        })
    }
    

    【讨论】:

    • 我要把这个添加到我的 util.js 中吗?
    • 对不起,我忘记了上下文...这应该替换您的 fetch 函数中的 addName 调用。
    • 当我点击按钮时,我仍然遇到它没有任何结果的问题,所以我假设存在连接问题。如果我输入“SELECT * FROM times”,它只会返回我手动输入的内容。我上面的 util.js 文件看起来正确还是我遗漏了什么?这是页面上的最后一件事
    • 我已经添加了完整的工作示例。有 cmets 解释出了什么问题。
    • 好的,我很感激。我的 index.js 设置为主页,使用 react,server.js 是节点文件。我可以调用上面的 App.js 和 util.js 吗?我正在尝试从渲染调用您在 App.js 中的内容
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 2020-08-05
    • 2011-09-11
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多