【问题标题】:Express not rendering page after a POST request在 POST 请求后 Express 不呈现页面
【发布时间】:2021-03-11 23:41:42
【问题描述】:

我的目标是让 onclick 函数发送一个发布请求以从页面​​上删除 HTML li。发布请求使用猫鼬函数删除数据,然后我希望重新加载页面,以便用户看到没有他们删除的项目的新页面。删除工作正常,但是我必须刷新页面才能看到它被删除。没有任何错误消息。

车库.翡翠

doctype html 
html(lang='en')
  head  
    script 
       include ../Scripts/garage_scripts.js 
    
  body 
    h1 Welcome to The Garage
      h2= title
      ul
      - for (let i=0; i<list_o_cars.length; i++)
        li(onclick='delete_car(this)', id="cars")= list_o_cars[i]

garage_scripts.js

function delete_car(target) {
  const data = {
    car: target.innerHTML,
  };

  const url = "http://localhost:3000/car_module/delete";
  let request_param = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(data),
  };

  fetch(url, request_param);
}

controller.js

exports.delete = function (req, res, next) {
res.send("hi") 
[enter image description here][1]//this would be a render but I am just testing to see if it will reload or redirect to a new page

这是请求预览的图片

【问题讨论】:

  • 页面不会自行重新渲染。您要么必须使用 javascript 手动重新加载页面(可能不是一个好方法),要么使用 javascript 删除li,当用户最终重新加载页面时,数据将消失。
  • 发送响应 "res.send('hi') 后你想做什么?

标签: javascript node.js express pug


【解决方案1】:

由于 fetch 返回一个承诺,您可以使用 .then() 解决它并重新加载页面。

fetch(url, request_param).then(function(res) { 
    window.location.reload();
}).catch(function(error) {
    console.log(error);
});

【讨论】:

    【解决方案2】:

    也许只是在 fetch() 之后添加window.location.reload();。 有人比我更好地解释了这一点,HERE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多