英文:
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:
<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 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)=>{
//const txt = req.body;
console.log('logged data: ',req.body);
res.send('Thanks');
})
app.listen(8080, () => {
console.log('server is running...in port 8080')
});
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("http://localhost:8080/login", 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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论