提问者:小点点

nodejs获取未定义-获取后[closed]


我试图将表单数据作为JSON从JS发送到Node.JS,以便使用express-validator对其进行验证,但是Node.JS总是得到一个undefined值。还尝试通过XMLHttpRequest而不是fetch发送它,但结果是相同的。只有当我从HTML发送表单时,它才能正确地获取数据。我不明白问题出在哪里。

HTML:

<form action="/send" method="POST" class="form" id="form" accept-charset="utf-8" onsubmit="return(validate())">
        <div id="error--box"></div>
        <div class="form__div">
            <label class="form__label" for="name">Your name</label>
            <input id="name" name="name" class="form__input" type="text">
        </div>
        <div class="form__div">
            <label class="form__label" for="email">Your e-mail</label>
            <input id="email" name="email" class="form__input" type="text">
        </div>
        <div class="form__div">
            <label class="form__label" for="message">Your message</label>
            <textarea name="message" id="message" class="form__input" cols="10" rows="4"></textarea>
        </div>
        <button class="form__submit" type="submit">Submit</button>
    </form>

JS:

const validate = () => {
const formData = new FormData(document.querySelector('#form'));

fetch('/send', {
    method: 'POST',
    headers: { 'ContentType': 'application/json', 'charset': 'utf-8'},
    data: 'json',
    body: JSON.stringify({
        name: formData.get('name'),
        email: formData.get('email'),
        message: formData.get('message')
    }),
})
.then(res => {
    if(res.ok) {
        return res.json();
    } else {
        return console.log('error');
    }
})
.then(data => console.log(data))
.catch(err => console.log(err))
return false;
}

JS从验证中注销所有错误列表。然后

node.js:

const express = require('express');
const { check, validationResult } = require('express-validator');

const app = express();
app.use(express.static('./public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.listen(3000);

app.get('/', (req, res) => {
   res.sendFile('index.html', { root: __dirname });
   res.end();
})

app.post('/send', [

check('name').isLength({ min: 2, max: 14 }),
check('email').isLength({ min: 1, max: 50}),
check('message').isLength({ min: 1})

], (req, res) => {
    console.log(req.body.name);
const errors = validationResult(req);
if(!errors.isEmpty()) {
    return res.json({ error: errors.array() });
}})

共1个答案

匿名用户

正如@Quentin指出的那样,在fetch(或XMLHttpRequest)操作中,您的Content-Type头应该是这样的。

headers: { 'Content-Type': 'application/json;charset=utf-8'},

express依赖于此来确定如何解释POST请求中的有效负载(数据)。如果没有它,express就无法找到如何用您的数据填充req.body