【问题标题】:What headers need to be sent with post request发布请求需要发送哪些标头
【发布时间】:2020-11-30 18:55:42
【问题描述】:

我正在使用邮递员测试服务器,一切正常,因为我得到了答案:

但是,如果我从浏览器向同一地址发出 post 请求,则会引发错误并且答案未定义

Postman 有以下标题:

如何正确发送帖子请求以获得响应?

主文件(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();

和路由器:

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;

据我了解,问题出在 expressValidator 中。

更新


我尝试使用 formData,但它不起作用。

【问题讨论】:

  • 嗯,你的标题与 Postman 的标题明显不同。
  • @RobertHarvey,是的,但是邮递员中的大多数标题只需要使其工作,正如邮递员本身所写的那样。也许我没明白什么。请帮我弄清楚
  • 如果网站没有看到它期望的标题,它将拒绝请求。
  • "我尝试使用 formData,但它不起作用。" 这可能是因为您在后一个示例中尝试访问完全不同的端点?

标签: javascript node.js express express-validator


【解决方案1】:

您期待 x-www-form-encoded,但您发送的是 json。

你应该这样做

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' });

}


}

【讨论】:

  • 来自邮递员,您发送 x-www-form-url 内容类型,但在您的获取中,您使用的是 application/json 。我的回答有什么问题,你试过了吗?
  • 我添加了截图
猜你喜欢
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2022-06-25
  • 1970-01-01
相关资源
最近更新 更多