【问题标题】:EXPRESS GET info on user快速获取用户信息
【发布时间】:2020-04-21 15:20:34
【问题描述】:

您好,我希望能够将用户传递到获取请求中,以查看他们发布了哪些项目。

这里是 GET 请求

// @route  GET with NAME
// @desc   GET All ITEMS WITH NAME
// @access private
router.get('/:user', (req, res) => {
    Item.findBy(req.params.user)
        .sort({ date: -1})
        .then(items => res.json(items))    
});

然后我希望能够通过操作文件传递它。

export const getItems = () => dispatch => {
    dispatch(setItemsLoading());
    axios.get(`/api/items/`).then(res => 
            dispatch({
                type: GET_ITEMS,
                payload: res.data
            })
            )
            .catch(err => 
                dispatch(returnErrors(err.response.data, err.response.status))
            );
    }

如果有人想知道,这里是项目模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//Create Schema
const ItemSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    user:{
        type: String,
        required: true
    },
    date:{
        type: Date,
        default: Date.now
    }
});

module.exports = Item = mongoose.model('item', ItemSchema);

这样的预期结果是

http://localhost:3000/{用户名}

产品列表 “名称”:“项目名称” “日期”:“月/日/年”

我也是 mongoDB/Json 的新手。我来自使用 SQL。

【问题讨论】:

    标签: node.js json express mongoose


    【解决方案1】:

    在这种情况下,我将使用req.query.user,而网址将是http://localhost:3000/?username

    然后在router.get方法中从mongoDB和res.send数据拉取正确的db数据到客户端。

    【讨论】:

    • ``` router.get('/:user', (req, res) => { try{ const user = await.findBy(req.query.user) res.send(user) }catch(err){ res.json({message : err}) } }); ``` 我试过了,但它不起作用。我只是收到一条错误消息。我应该如何调试这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多