如何将提交的表单数据发送到本地服务器

I0_ol

我正在尝试使用React和Node构建一个非常基本的全栈应用程序。我无法让前端将数据发送到服务器。我进入POST http://localhost:4000/ 500 (Internal Server Error)控制台。我需要怎么做才能将用户提交的数据发送到服务器,以便可以将其存储在数据库中?

我的反应码

class App extends React.Component {
    constructor() {
        super();
        this.state = {text: ''}
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }
    handleSubmit(e) {
        e.preventDefault();
        fetch('http://localhost:4000/users', {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: this.state.text // trying to send this text to the server
        })
            .then((response) => {
                console.log('success writing to server', response)
            })
            .catch((err) => {
                console.log('error writing to server', err);
            })
    }

    handleChange(e) {
        this.setState({
            text: e.target.value
        })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input onChange={this.handleChange} type="text" placeholder="Name" ref="name" />
                <input type="submit" />
            </form>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

我的服务器代码:

const express = require('express');
const mysql = require('mysql');

const port = process.env.port || 4000;
const app = express();

let db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'my_db'
})


app.use(express.static('public'));

app.post('/users', function (req, res) {
    console.log(req.body) // undefined
    // I would have thought that req.body.text would work but req.body is undefined
    db.query(`INSERT INTO users (user) VALUES ("${req.body.text}")`, function (err, result) {
        if (err) {
            console.log('error inserting into database', err.sqlMessage);
        } else {
            console.log('successful insertion into database', result);
        }
    });
    res.sendStatus(201);
});
app.listen(port, 'localhost');
Treycos

通过"Content-Type": "application/json"在请求中指定,您可以告诉服务器它将要接收JSON对象。
但是,您要发送的正文是this.state.text输入中的原始值,字符串而不是JSON,这就是为什么服务器将其视为未定义的原因。

您首先需要将其放入JSON中,然后将其字符串化,然后再将其发送到服务器:

fetch('http://localhost:4000/users', {
    method: "POST",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({ textInput: this.state.text })
})

解决的另一种方法是告诉服务器它将接收原始文本:

fetch('http://localhost:4000/users', {
    method: "POST",
    headers: {"Content-Type": "text/plain"}, //Expects a raw text body
    body: this.state.text
})

您可以在以下文档中看到有关如何使用访存的更精确的解释:https : //developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Spring MVC中将用户表单数据发送到服务器

在AngularJS中将表单数据发送到服务器

如何通过进行Ajax调用将html表单数据发送到node.js服务器?

如何使用angular 2将表单数据发送到服务器api?

无法获取从角度发送到节点服务器的表单数据

如何将“数据”和“结束”事件从cURL发送到nodejs的HTTP服务器?

如何使用angularjs将多个表单数据一次性发送到服务器?

如何使用node.js将表单数据从客户端脚本发送到服务器脚本

ASP.NET表单-如何将表单数据发送到外部WCF服务

有没有办法在提交表单之前修改将要发送到服务器的表单数据?

NextJS:表单数据未发送到快递服务器

如何使用Volley将JSONObject作为表单数据发送到服务器

Chrome并不总是将表单数据发送到我的(自行实施)服务器

Apollo Client如何将本地缓存的变异发送到服务器

如何使用angular将表单数据发送到服务器?

为什么POST方法将两次表单数据发送到服务器?

如何将String数组作为发布数据发送到Web服务器?

如何将HTML表单数据发送到Java http服务器

如何将日志从本地服务器发送到AWS Cloudwatch?

通过节点中间人将表单数据发送到Java服务器

在提交时将表单数据发送到Javascript

远程Internet服务器如何将数据包发送到本地IP?

将表单数据中的 dropdwon 选定列表项发送到服务器

React 和 NodeJS:如何将数据从服务器发送到客户端?

如何将表单数据从客户端发送到服务器

如何将表单数据提交到快递服务器?

有没有办法在表单提交后防止重定向并仍然将表单数据发送到服务器?

如何将表单数据发送到链接?

如何使用登录表单将数据从 React 发送到 Node 服务器?