【问题标题】:How to fix a "reload page loop" when using a post method in Node JS?在 Node JS 中使用 post 方法时如何修复“重新加载页面循环”?
【发布时间】:2021-05-13 18:18:35
【问题描述】:

给定以下 html 表单:

<form class = "new-date" method = "POST" action = "http://localhost:5600/postDate">
                <h3>Owner</h3>
                <input type ="text" name = "ownerName" class = "form-element global"  id="owner">
                </select>
                <h3>Pet</h3>
                <input type = "text" name = "petName" class = "form-element global" id = "pet">
                </select>
                <h3>Schedule the date</h3>
                <input type="date" id="birthday" name="birthday" class = "form-element global"  id="date">
                <h3>Description</h3>
                <textarea class = "form-element description-text" placeholder= "What is wrong with your pet?" name ="problem" ></textarea  id="problem"><br>
                <input type="submit" class = "form-element btn" value="Add">
</form>

我正在尝试创建一个位于我的 server.js(节点)内的 post 方法:

const exp = require('express');
const path = require('path');
var bodyParser  = require('body-parser');
const app = exp();

/*DATABASE AND QUERIES*/ 
const mysql = require("mysql2"); 

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "admin",
    database: "control_clientes",
    connectionLimit: 5
});

app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.post('/postDate', (req, res)=>{
    console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
});

提交客户端数据并将其发送到我的服务器后,html页面没有正确执行重新加载任务:

As can see in this image, the reload thing is still going. I'm not sure why it does that.

我是 Node JS 的新手,你知道未完成的重新加载是怎么回事吗?

【问题讨论】:

  • 你需要真正从路由返回响应

标签: javascript html node.js express post


【解决方案1】:

试试这个

app.post('/postDate', (req, res)=>{
   console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
   res.json({message: 'OK.'})
});

【讨论】:

    【解决方案2】:

    如果您希望浏览器停止旋转(加载),您需要从服务器发送响应。 例如发送一个带有 req.body(回显端点)的 json 响应

    app.post('postDate', (req, res) => {
        console.log(req.body.ownerName);
        res.json(req.body);
    })
    

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 1970-01-01
      • 2019-12-27
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多