【问题标题】:How to post some json data to a route in api如何将一些json数据发布到api中的路由
【发布时间】:2021-03-12 01:43:26
【问题描述】:

我在 NodeJs 中创建了一个非常简单的 API。代码如下:

const Post = require('../models/article');
...
router.post('/contribute', (req, res) => {
    console.log('Pushing new article');
    let userPost = req.body;
    let post = new Post(userPost);
    post.save((error, registeredPost) => {
        if (error) {
            console.log(error);
        } else {
            res.status(200).send(registeredPost);
        }
    })
})
...
module.exports = router;

帖子的结构是这样的:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
    articleid: String,
    title: String,
    content: String,
    date: String,
    contributor: String,
    upvotes: Number,
    upvoters: [String],
    downvotes: Number,
    downvoters: [String]
})
module.exports = mongoose.model('article', articleSchema, 'articles');

这里是 server.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

const api = require('./routes/api');
const cors = require('cors');

app.use(bodyParser.json());
app.use(cors());

app.use('/api', api);
app.get('/', function(req, res) {
    res.send('Server is up and running!');
})

app.listen((3000), function() {
    console.log('Server listening on heroku environment port');
});

理想情况下,数据应该来自有角度的表单/模板,但在推送代码之前,我想在 Postman 上进行测试。这是截图:

我明白了:

无法发布/贡献

请指出我的错误。

【问题讨论】:

  • 你在 index.js 中添加了app.use(express.json({ extended: true })); 吗?
  • 您是否已将路由器导出到路由文件module.exports = router; 中?
  • @TalESid,是的,我做到了。
  • 只有在找不到 POST 路由 /contribute 时才会发生这种情况!
  • 那你为什么用router.post?如果没有单独的路由文件,在 index.js 中使用app.post

标签: node.js angular express npm postman


【解决方案1】:

我没有注意到我点击了错误的 URL。

错误:

localhost:3000/contribute

正确:

localhost:3000/api/contribute

现在一切正常,我也从服务器获得了正确的 json 响应。

【讨论】:

    【解决方案2】:

    因为你正在使用:

    app.use('/api', api)
    

    所以,请务必使用此端点:

    localhost:3000/api/contribute
    

    现在,它可以正常工作了。

    【讨论】:

    • 是的,我也刚刚发布了这个答案。也许我们同时想到了这一点。既然你努力了,我接受你的。 :-)
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多