无法从axios发送数据到我的Node服务器,该服务器返回空对象。

huangapple go评论65阅读模式
英文:

not able to sent data from axios to my node server which returns empty object

问题

My client-side code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="form.css" />
  </head>
  <body>
    <form action="/login" method="post" class="form">
      <input type="text" name="txt" class="txt" id="txt" placeholder="name" />
      <input type="submit" class="submit" id="submit" />
    </form>
    <script defer src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let submit = document.querySelector(".submit");
      const form = document.querySelector(".form");

      form.addEventListener("submit", (e) => {
        e.preventDefault();

        const formData = new FormData(form);

        const formObject = {};
        formData.forEach((value, key) => {
          formObject[key] = value;
        });

        console.log(axios.defaults);

        axios
          .post("http://localhost:8080/login", formObject)
          .then(function (response) {
            console.log(response.data);
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    </script>
  </body>
</html>

My server-side code:

const express = require("express");

const app = express();
const path = require("path");

app.use(express.static('./public',{index:'form.html'}));

app.use(express.urlencoded({extended:true}));

app.post('/login',(req,res)=>{
  console.log('logged data: ',req.body);
  res.send('Thanks');
});

app.listen(8080, () => {
  console.log('server is running...in port 8080')
});

请注意,我已经将您提供的代码部分翻译成中文,其他部分保持原样。

英文:

my client-side code:

&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot; /&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
&lt;title&gt;Document&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;form.css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;/login&quot; method=&quot;post&quot; class=&quot;form&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;txt&quot; class=&quot;txt&quot; id=&quot;txt&quot; placeholder=&quot;name&quot; /&gt;
&lt;input type=&quot;submit&quot; class=&quot;submit&quot; id=&quot;submit&quot; /&gt;
&lt;/form&gt;
&lt;script defer src=&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
let submit = document.querySelector(&quot;.submit&quot;);
const form = document.querySelector(&quot;.form&quot;);
form.addEventListener(&quot;submit&quot;, (e) =&gt; {
e.preventDefault();
const formData = new FormData(form);
const formObject = {};
formData.forEach((value, key) =&gt; {
formObject[key] = value;
});
console.log(axios.defaults)
axios
.post(&quot;http://localhost:8080/login&quot;, formObject)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
});
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

my server side code :


const app = express();
const path = require(&quot;path&quot;);
app.use(express.static(&#39;./public&#39;,{index:&#39;form.html&#39;}));
app.use(express.urlencoded({extended:true}));
app.post(&#39;/login&#39;,(req,res)=&gt;{
//const txt = req.body;
console.log(&#39;logged data: &#39;,req.body);
res.send(&#39;Thanks&#39;);
})
app.listen(8080, () =&gt; {
console.log(&#39;server is running...in port 8080&#39;)
});

First of all please keep in mind that I am new to the backend. when I try to console.log the logged data it's returning me an empty object I can't understand why my req.body is returning an empty object but when I try to do the same by giving action:"/login" and method: "post" inside the form tag it works as expected and gives me the input I provide. Please someone help me my head is burning and thankyou in advance.

答案1

得分: 1

req.body是空的,因为当您使用axios发送请求时,实际上是发送JSON(application/json)有效载荷,而后端没有JSON有效载荷解析器,只有URL编码的解析器,而HTML表单以application/x-www-form-urlencoded格式发送数据,这就是为什么它能正常工作的原因。

因此,您需要使用axios发送URL编码的请求,可以使用URLSearchParams将JSON对象转换为查询字符串。尝试这样做:

axios
  .post("http://localhost:8080/login", new URLSearchParams(formObject))

或者,简单地在后端添加一个JSON解析器,您的原始JSON请求将正常工作,可以使用内置的解析器:

app.use(express.json());
英文:

req.body is empty because when you send it with axios, you're actually sending a JSON (application/json) payload, and you don't have a JSON payload parser on backend, only URL-encoded, while the HTML form sends it in the application/x-www-form-urlencoded format, which is why it works.

So, you need to send URL-encoded request with axios, you can use URLSearchParams to convert JSON object to query string. Try this.

axios
.post(&quot;http://localhost:8080/login&quot;, new URLSearchParams(formObject))

Or, simply add a JSON parser to the backend, and your original JSON request will work, use built in parser:

app.use(express.json());

huangapple
  • 本文由 发表于 2023年5月21日 19:08:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定