【发布时间】: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.js 和 npm 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