http:// localhost:3000 / api / stuff的Http失败响应:400错误的请求

Mehmeto

我正在尝试学习如何将对象保存到Mongoose DB中。即使看起来我已经正确完成了所有操作,但我仍然Http failure response for http://localhost:3000/api/stuff: 400 Bad Request在浏览器中得到一个不该出现的浏览器。这个错误对我来说意义不大。我的要求出了什么问题?

我可能错过了一些东西。

app.post('/api/stuff', (req, res, next) => {
    delete req.body._id;
    const thing = new Thing({
        ...req.body
    });
    thing.save()
        .then(() => res.status(201).json({ message: 'Objet enregistré !'}))
        .catch(error => res.status(400).json({ error }));
});

完整的app.js代码:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const Thing = require('./models/thing');

mongoose.connect(
        'mongodb+srv://username:[email protected]/test?retryWrites=true&w=majority',
        { useNewUrlParser: true, useUnifiedTopology: true }
    ).then(() => console.log('Connexion à MongoDB réussie !'))
    .catch(() => console.log('Connexion à MongoDB échouée !'));

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'
    );
    res.setHeader(
        'Access-Control-Allow-Methods',
        'GET, POST, PUT, DELETE, PATCH, OPTIONS'
    );
    next();
});

app.use(bodyParser.json());

app.post('/api/stuff', (req, res, next) => {
    delete req.body._id;
    const thing = new Thing({
        ...req.body
    });
    thing.save()
        .then(() => res.status(201).json({ message: 'Objet enregistré !'}))
        .catch(error => res.status(400).json({ error }));
});


app.use('/api/stuff', (req, res) => {
    const stuff = [
        {
            _id: 'oeihfzeoi',
            title: 'Mon premier objet',
            description: 'Les infos de mon premier objet',
            imageUrl: 'https://cdn.pixabay.com/photo/2019/06/11/18/56/camera-4267692_1280.jpg',
            price: 4900,
            userId: 'qsomihvqios',
        },
        {
            _id: 'oeihfzeomoihi',
            title: 'Mon deuxième objet',
            description: 'Les infos de mon deuxième objet',
            imageUrl: 'https://cdn.pixabay.com/photo/2019/06/11/18/56/camera-4267692_1280.jpg',
            price: 2900,
            userId: 'qsomihvqios',
        },
    ];
    res.status(200).json(stuff);
});

module.exports = app;

Thing.js:

const mongoose = require('mongoose');

const thingSchema = mongoose.Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    imageURL: { type: String, required: true },
    userId: { type: String, required: true },
    price: { type: Number, required: true },
});

module.exports = mongoose.model('Thing', thingSchema);

编辑:

如果我控制台日志req.bodyerror我得到这个:

[nodemon] starting `node server.js`
Listening on port 3000
Connexion à MongoDB réussie !
{
  title: 'sadfsaf',
  description: 'sdf fds sag asdf',
  price: 12300,
  imageUrl: 'sadf',
  userId: 'userID40282382'
}
Error [ValidationError]: Thing validation failed: imageURL: Path `imageURL` is required.
    at ValidationError.inspect (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/error/validation.js:61:24)
    at formatValue (internal/util/inspect.js:563:31)
    at inspect (internal/util/inspect.js:221:10)
    at formatWithOptions (internal/util/inspect.js:1693:40)
    at Object.Console.<computed> (internal/console/constructor.js:272:10)
    at Object.log (internal/console/constructor.js:282:61)
    at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/app.js:36:21
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  errors: {
    imageURL: MongooseError [ValidatorError]: Path `imageURL` is required.
        at new ValidatorError (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/error/validator.js:29:11)
        at validate (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1061:13)
        at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1115:11
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (/mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/schematype.js:1070:14)
        at /mnt/c/Users/Shadow/Development/scottish_nodejs/backend/node_modules/mongoose/lib/document.js:2303:9
        at processTicksAndRejections (internal/process/task_queues.js:75:11) {
      message: 'Path `imageURL` is required.',
      name: 'ValidatorError',
      properties: [Object],
      kind: 'required',
      path: 'imageURL',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Thing validation failed',
  name: 'ValidationError'
}
苏莱曼·萨

imageURL在架构定义中具有必填字段。但是在您使用的req.body中imageUrl,所以猫鼬会给出该错误。

如果您以这种方式发送您的req.body,它将起作用:

{
    "title": "sadfsaf",
    "description": "sdf fds sag asdf",
    "price": 12300,
    "imageURL": "sadf",
    "userId": "userID40282382"
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

身份验证POST http:// localhost:3000 / api / users / register 400(错误请求)MERN应用

来自分类Dev

$ .getJSON将'http:// localhost:3000'添加到api URL

来自分类Dev

POST http:// localhost:3000/404(未找到)

来自分类Dev

无法访问 http://localhost:3000/

来自分类Dev

ruby - 运行 http://localhost:3000/admin/users 但redirect_to http://localhost:3000/admin/login

来自分类Dev

POST http://localhost:3000/signin 400 (Bad Request) in react

来自分类Dev

尝试使用“ http:// localhost:61961 / Token”登录到Web API。收到400错误的请求错误

来自分类Dev

代理错误:无法将请求 /users 从 localhost:3000 代理到 http://localhost:3001/

来自分类Dev

从源“null”访问 Twitter_OAuth_Url(从“http://localhost:3000/api/twitter-login”重定向)的 XMLHttpRequest 已被阻止

来自分类Dev

意外的请求:POST / api / v1 / auth / sign_in预期的POST http:// localhost:3000 / api / v1 / auth / sign_in

来自分类Dev

在 React 中将所有内容放在 http://localhost:3000/app 而不是 http://localhost:3000/ 下的最简单方法

来自分类Dev

POST http:// localhost:3000 / socket.io /?EIO = 3&transport = polling&t = NQUneY3 400(错误请求)在ejs和nodejs中

来自分类Dev

错误:正在加载http:// localhost:3000 / rxjs / RX(…)的XHR错误(找不到404)

来自分类Dev

在http:// localhost:3000 / entries / view_all上引发错误

来自分类Dev

XHR错误(找不到404)载入http:// localhost:3000 / @ angular / core

来自分类Dev

无法从API接收HTTP响应-错误的请求错误

来自分类Dev

HTTP / 1.1 400错误请求Sabre REST Api

来自分类Dev

HTTP请求失败!HTTP / 1.1 400错误请求

来自分类Dev

ERR_CONNECTION_REFUSED http:// localhost:3000 / socket.io / socket.io.js

来自分类Dev

Ember CLI和Rails:代理到http:// localhost:3000时出错

来自分类Dev

从http:// localhost:3000 / app / main.js加载“ @ angular / platform-browser-dynamic”时出错

来自分类Dev

GET http:// localhost:3000 / components / t.mp3 net :: ERR_ABORTED 404(未找到)

来自分类Dev

react-full-page会阻止我的页面以特定ID(例如http:// localhost:3000 /#someIdWhereIWantThePageToBeOpened)打开

来自分类Dev

拒绝从'http:// localhost:3000 / style.css'应用样式,因为它的MIME类型('text / html')

来自分类Dev

GET http:// localhost:3000/404(未找到),实际上是在拨打POST却获得GET

来自分类Dev

如何从user_path(:current)获取“ http:// localhost:3000 / users / current”?

来自分类Dev

启用了热模块替换,但无法正常使用http:// localhost:3000 / __ webpack_hmr

来自分类Dev

CORS 策略阻止了从源“http://localhost:3000”获取 $AWS_LAMBDA_SITE 的访问权限

来自分类Dev

WCF请求失败,HTTP状态为400错误。元数据包含无法解析的引用:http://localhost/MyService.svc/mex

Related 相关文章

  1. 1

    身份验证POST http:// localhost:3000 / api / users / register 400(错误请求)MERN应用

  2. 2

    $ .getJSON将'http:// localhost:3000'添加到api URL

  3. 3

    POST http:// localhost:3000/404(未找到)

  4. 4

    无法访问 http://localhost:3000/

  5. 5

    ruby - 运行 http://localhost:3000/admin/users 但redirect_to http://localhost:3000/admin/login

  6. 6

    POST http://localhost:3000/signin 400 (Bad Request) in react

  7. 7

    尝试使用“ http:// localhost:61961 / Token”登录到Web API。收到400错误的请求错误

  8. 8

    代理错误:无法将请求 /users 从 localhost:3000 代理到 http://localhost:3001/

  9. 9

    从源“null”访问 Twitter_OAuth_Url(从“http://localhost:3000/api/twitter-login”重定向)的 XMLHttpRequest 已被阻止

  10. 10

    意外的请求:POST / api / v1 / auth / sign_in预期的POST http:// localhost:3000 / api / v1 / auth / sign_in

  11. 11

    在 React 中将所有内容放在 http://localhost:3000/app 而不是 http://localhost:3000/ 下的最简单方法

  12. 12

    POST http:// localhost:3000 / socket.io /?EIO = 3&transport = polling&t = NQUneY3 400(错误请求)在ejs和nodejs中

  13. 13

    错误:正在加载http:// localhost:3000 / rxjs / RX(…)的XHR错误(找不到404)

  14. 14

    在http:// localhost:3000 / entries / view_all上引发错误

  15. 15

    XHR错误(找不到404)载入http:// localhost:3000 / @ angular / core

  16. 16

    无法从API接收HTTP响应-错误的请求错误

  17. 17

    HTTP / 1.1 400错误请求Sabre REST Api

  18. 18

    HTTP请求失败!HTTP / 1.1 400错误请求

  19. 19

    ERR_CONNECTION_REFUSED http:// localhost:3000 / socket.io / socket.io.js

  20. 20

    Ember CLI和Rails:代理到http:// localhost:3000时出错

  21. 21

    从http:// localhost:3000 / app / main.js加载“ @ angular / platform-browser-dynamic”时出错

  22. 22

    GET http:// localhost:3000 / components / t.mp3 net :: ERR_ABORTED 404(未找到)

  23. 23

    react-full-page会阻止我的页面以特定ID(例如http:// localhost:3000 /#someIdWhereIWantThePageToBeOpened)打开

  24. 24

    拒绝从'http:// localhost:3000 / style.css'应用样式,因为它的MIME类型('text / html')

  25. 25

    GET http:// localhost:3000/404(未找到),实际上是在拨打POST却获得GET

  26. 26

    如何从user_path(:current)获取“ http:// localhost:3000 / users / current”?

  27. 27

    启用了热模块替换,但无法正常使用http:// localhost:3000 / __ webpack_hmr

  28. 28

    CORS 策略阻止了从源“http://localhost:3000”获取 $AWS_LAMBDA_SITE 的访问权限

  29. 29

    WCF请求失败,HTTP状态为400错误。元数据包含无法解析的引用:http://localhost/MyService.svc/mex

热门标签

归档