获取不会从客户端发布到服务器端(node.js)

发布于 2025-01-25 03:55:24 字数 2029 浏览 3 评论 0原文

问题:我正在使用stackoverflow 成员的以下代码。我喜欢该代码,希望它能有效,但是它没有,正如我将要解释的那样:

目的:从客户端获取输入,使用JavaScript进行修改,然后将修改后的变量发布到服务器端(node.js/express)。

代码(归功于 kwh ):

<body>
  <script type="text/javascript">
    function customSubmit() {
      const name = document.getElementById('name').value + ' mock';
      const city = document.getElementById('city').value + ' mock';
      fetch('/posty', {
        method: 'POST',
        body: JSON.stringify({ name, city })
      })
    }
  </script>
  <form onsubmit="event.preventDefault(); customSubmit()">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
</body>

我有node.js and express.js serverside,而且我尚未安装node-fetch。我将eJS用作HTML的模板/文件,用于客户端。

客户端端代码:

app.post('/posty', (req,res) => {

    console.log(req.body)
 
})

返回控制台中的一个空对象(Linux终端):

{}

现在,如果我在代码中替换以下行:

<form onsubmit="event.preventDefault(); customSubmit()">

使用

<form action="/posty" method ="POST">

我将在控制台中获得一个非空对象:

{ name: 'John', city: 'Berlin' }

但是,这不是解决方案,因为我在将其发布到服务器端(Node.js)之前,必须修改该人的姓名和城市。

讨论:

我尚未为node.js安装node-fetch。即使,如果我安装了它,我也必须将模块导入node.js服务器文件,该文件在服务器端运行,而不是在客户端上运行。我看不到在node.js上安装node-fetch以使用fetch()在客户端兼容浏览器上运行的html/js代码发布。

上面给定代码中的某些内容可能是在服务器端或客户端或两者兼而有之。如果有人可以指出这一点,我将不胜感激。另外,我要感谢 kwh ,他提供了清洁和紧凑的代码,并帮助组织了我的研究以解决问题。

Problem: I am using the following code provided by StackOverflow members. I like the code, and I wish it worked, but it did not, as I will explain:

The Purpose: Take input from the Client-Side, modify it with JavaScript, then POST the modified variables to the Server-Side (Node.js/Express).

The Code (credit to kwh):

<body>
  <script type="text/javascript">
    function customSubmit() {
      const name = document.getElementById('name').value + ' mock';
      const city = document.getElementById('city').value + ' mock';
      fetch('/posty', {
        method: 'POST',
        body: JSON.stringify({ name, city })
      })
    }
  </script>
  <form onsubmit="event.preventDefault(); customSubmit()">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
</body>

I have node.js and express.js serverside, and I have not installed node-fetch. I use EJS as templating engine/file for HTML and JS for the Client-Side.

Client side code:

app.post('/posty', (req,res) => {

    console.log(req.body)
 
})

which returns an empty object in the console (Linux terminal):

{}

Now if I replace the following line in the code:

<form onsubmit="event.preventDefault(); customSubmit()">

with

<form action="/posty" method ="POST">

I will get a non-empty object in the console:

{ name: 'John', city: 'Berlin' }

However, this is not the solution because I have to modify the person's name and the city before POSTing it to the Server-Side (Node.js).

Discussion:

I have not installed node-fetch for node.js. Even, If I installed it, I would have to import the module in a node.js server file that runs on the Server-Side, not on the Client-Side. I cannot see the point of installing node-fetch on node.js to use fetch() to POST in HTML/JS code running on a compatible browser on the Client-Side.

Maybe something is missing in the given codes above, either on the Server-Side or Client-Side, or both. I would appreciate it if someone could point that out. Also, I want to thank kwh, who provided the clean and compact code and helped organize my research to solve the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

|煩躁 2025-02-01 03:55:24

您是否在路线前使用了尸体?您可以使用express.json()进行操作

app.use(express.json())
app.post('/posty', (req,res) => {

    console.log(req.body)
 
})

Did you use parsed the body before your routes? You can do it with express.json()

app.use(express.json())
app.post('/posty', (req,res) => {

    console.log(req.body)
 
})
捂风挽笑 2025-02-01 03:55:24

JavaScript比DOM快得多,这就是为什么您需要让浏览器首先渲染DOM,然后再执行JS。通过此完成,

document.addEventListener("DOMContentLoaded", function (event) {
  // content is loaded
  
  const form = document.getElementById("id-of-yow-form");
  form.addEventListener("submit", function (event) {
     event.preventDefault();
     //add yow code
  });

});

请确保将相同的ID添加到yow表单标签

 <form id="id-of-yow-form">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  

javascript is much faster than the dom, thats why you need to let the browser to render the dom first then to exec the js. it is done by this

document.addEventListener("DOMContentLoaded", function (event) {
  // content is loaded
  
  const form = document.getElementById("id-of-yow-form");
  form.addEventListener("submit", function (event) {
     event.preventDefault();
     //add yow code
  });

});

make sure to add the same id to yow form tag

 <form id="id-of-yow-form">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
东京女 2025-02-01 03:55:24

感谢您的回答。
我在 stackoverflow论坛

我必须在代码中添加以下行中的fetch()块,建议(客户端):

headers: new Headers({ "Content-Type": "application/json" })

另外,我在服务器端的代码上添加了以下行, ifaruki ifaruki 建议:

app.use(express.json())

因此,服务器端上缺少一行代码,而在客户端侧则缺少一行。我两个都需要。

再次感谢您的快速回复和帮助。

Thanks for your responses.
I find the solution with the help of two StackOverflow members and one of the other posts on StackOverflow forum:

I had to add the following line to fetch() block in the code that kwh suggested (Client-Side):

headers: new Headers({ "Content-Type": "application/json" })

Also, I added the following line to the code on the Server-Side as Ifaruki suggested:

app.use(express.json())

So one line of code was missing on the Server-Side and one on the Client-Side. I needed both.

Thanks again for your fast response and your help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文