Search code examples
javascriptnode.jsexpressexpress-validator

What headers need to be sent with post request


I'm testing the server using postman and everything works fine, in the sense that i get the answer:

enter image description here

But if I making post request from the browser to the same address it throws an error and the answer is undefined

enter image description here

Postman has the following headers:

enter image description here

How do I send a post request correctly to get a response?

Main file (App.js):

const express = require('express');
const config = require('config');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();

const corsOptions = {
    origin: config.get('CORS.whiteList'),
    optionsSuccessStatus: config.get('CORS.optionsSuccessStatus')
}

app.use(cors(corsOptions));

app.use('/api/auth', require('./routes/auth.routes'));

const PORT = config.get('PORT') || 5000;

async function startServer() {
    try {
        await mongoose.connect(config.get('mongoUri'), {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true
        });
        app.listen(PORT, () => console.log(`App has been started on port: ${PORT}`));
    } catch (err) {
        console.log(`Server error: ${err.message}`);
        process.exit(1);
    }
}

startServer();

And router:

const { body, validationResult } = require('express-validator');
const User = require('../models/User');
const config = require('config');
const bodyParser = require('body-parser');

const router = express.Router();

const jsonParser = bodyParser.json();

const urlencodedParser = bodyParser.urlencoded({ extended: false });

router.post('/login',
    urlencodedParser, [body('email', 'Некоректный email').isEmail()],
    async(req, res) => {
        try {
            const errors = validationResult(req);

            if (!errors.isEmpty()) {
                console.log(3)
                return await res.status(400).json({
                    errors: errors.array()[0].msg,
                    message: 'Некорректные данные при регистрации'
                })
            }

            const email = req;

            console.log(email)

            const candidate = await User.findOne({ email: email });

            console.log(3)

            if (candidate) {
                return await res.status(400).json({
                    msg: 'Такой email уже зарегестрирован'
                });
            }

            const user = new User({
                email
            });

            await user.save();

        } catch (err) {
            console.log(err)
            return await res.status(500).json({
                msg: 'Что-то пошло не так, попробуйте снова',
                err: err.stack
            });
        }
    }
);

module.exports = router;

As I understand it, the problem is in expressValidator.

UPD


I've tryed to use formData, but it doesn't working.

enter image description here


Solution

  • you are expecting x-www-form-encoded, but you are sending json.

    you should do this

    const onSubmit = () => {
           
    
    fetch(url, 
         { method: 'post', 
             headers: {
                 { /* depending on server, this may not be needed */}
                'Content-Type': 'application/x-www-form-urlencoded'
           },
          body: new URLSearchParams({ 'email': 'daw' });
    
    }
    
    
    }