[英]post request returns empty object
I am trying to send form data to the backend using fetch API but when I console.log my request.body
it returns an empty object {}
.我正在尝试使用 fetch API 将表单数据发送到后端,但是当我 console.log 我的request.body
它返回一个空的 object {}
。 What I was trying to send to my backend was the firstname, lastname, email, and message the user inputted.我试图发送到后端的是名字、姓氏、email,以及用户输入的消息。 Why isn't the object containing the data.为什么 object 不包含数据。 Where did I go wrong.我在哪里 go 错了。 Any help is appreciated.任何帮助表示赞赏。 Thanks in advance.提前致谢。
//backend const express = require('express'); const app = express(); app.listen(3000, () => console.log('listening at port 3000')); app.use(express.static('public')); app.use(express.json({ limit: '1mb' })); app.post('/api', (request, response) => { console.log('I got a request') //Prints I got a request console.log(request.body); //Prints {} (empty object) });
//frontend function proccessContactMessage() { firstName = document.getElementById('contactUsFirstName').value lastName = document.getElementById('contactUsLastName').value email = document.getElementById('contactUsEmail').value message = document.getElementById('contactUsMessage').value const data = { firstName, lastName, email, message }; const options = { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; fetch('http://localhost:3000/api', options); }
<form class="formContactUs"> <div class="contactUsTitleCon"> <h2 class="contactUsTitle">Contact Us</h2> </div> <div class="form-group"> <label for="contactUsFirstName">First Name</label> <input type="text" class="form-control" id="contactUsFirstName" placeholder="Enter First Name" required> </div> <div class="form-group"> <label for="contactUsLastName">Last Name</label> <input type="text" class="form-control" id="contactUsLastName" placeholder="Enter Last Name" required> </div> <div class="form-group"> <label for="contactUsEmail">Email</label> <input type="email" class="form-control" id="contactUsEmail" placeholder="Enter Email" required> </div> <div class="form-group"> <label for="contactUsMessage">Message</label> <textarea class="form-control" id="contactUsMessage" placeholder="Enter Message" required></textarea> </div> <div class="contactUsSubmitBtnCon"><button type="submit" class="btn btn-primary contactUsSubmitBtn" onclick="proccessContactMessage()">Submit</button></div> </form>
Remove mode: 'no-cors'
from the options
.从options
中删除mode: 'no-cors'
。
This should give you the desired result.这应该会给你想要的结果。
The no-cors
mode doesn't support the Content-Type: application/json
header . no-cors
模式不支持Content-Type: application/json
header 。 Try to set up a CORS header and remove the mode: 'no-cors'
property.尝试设置 CORS header并删除mode: 'no-cors'
属性。
As I can understand from our exchange of comments in my first answer, the problem comes from the CORS.正如我在第一个答案中的评论交流中所理解的那样,问题来自 CORS。 If so, try this:如果是这样,试试这个:
const cors = require('cors');
const corsOptions = {
origin: (origin, callback) => {
callback(null, true);
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Access-Control-Allow-Origin", "Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"],
credentials: true
};
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
I guess, you need a body parser !我想,你需要一个身体解析器! You can use the body-parser
or the express.urlencoded()
.您可以使用body-parser
或express.urlencoded()
。
Try this:尝试这个:
In your app.js:在您的 app.js 中:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));// we need to register a parser, to parse the incoming request body !
Or, you can replace that with:或者,您可以将其替换为:
app.use(express.urlencoded({ extended: true })); //Parse URL-encoded bodies
Then, you can do:然后,你可以这样做:
console.log(req.body);
In the function proccessContactMessage() you defined data as:在 function proccessContactMessage() 中,您将数据定义为:
const data = {
firstName,
lastName,
email,
message
};
But this is not a valid JSON object.但这不是有效的 JSON object。
//frontend function proccessContactMessage() { firstName = document.getElementById('contactUsFirstName').value lastName = document.getElementById('contactUsLastName').value email = document.getElementById('contactUsEmail').value message = document.getElementById('contactUsMessage').value const data = { firstName: firstName, lastName: lastName, email: email, message: message }; console.log(data); const options = { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; fetch('http://localhost:3000/api', options); }
<form class="formContactUs"> <div class="contactUsTitleCon"> <h2 class="contactUsTitle">Contact Us</h2> </div> <div class="form-group"> <label for="contactUsFirstName">First Name</label> <input type="text" class="form-control" id="contactUsFirstName" placeholder="Enter First Name" required> </div> <div class="form-group"> <label for="contactUsLastName">Last Name</label> <input type="text" class="form-control" id="contactUsLastName" placeholder="Enter Last Name" required> </div> <div class="form-group"> <label for="contactUsEmail">Email</label> <input type="email" class="form-control" id="contactUsEmail" placeholder="Enter Email" required> </div> <div class="form-group"> <label for="contactUsMessage">Message</label> <textarea class="form-control" id="contactUsMessage" placeholder="Enter Message" required></textarea> </div> <div class="contactUsSubmitBtnCon"><button type="submit" class="btn btn-primary contactUsSubmitBtn" onclick="proccessContactMessage()">Submit</button></div> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.