首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node JS,vanilla JS

Node JS,vanilla JS
EN

Stack Overflow用户
提问于 2021-11-17 12:10:37
回答 1查看 94关注 0票数 0

我在vanilla JS中编写了一个简单的函数fetch来从api获取te数据。我想使用node js将这些数据发送到我的数据库mongodb。我知道这段代码很混乱,但我的朋友在后台工作,我在前端工作,我们正在尝试合并这些代码。我不知道如何处理create function中的'req‘参数。谢谢你的帮助。

代码语言:javascript
复制
const Match = require('../db/models/match');

class MatchController {
    async showMatches(req, res) {        
        const matches = await Match.find();
        res.status(200).json(matches); //parsuje dane na JSON 
        console.log('show');
    }

    async create(req, res) { 

        const match = getDataForSheduleCJS(nameLeague).then(resp => {
            const matchObject = new Match({
                leagueName: resp.competition.name,
                date: resp.utcDate.slice(0, 10),
                awayTeam: resp.awayTeam.name,
                homeTeam: resp.homeTeam.name,
                scoreHomeTeam: resp.score.fullTime.homeTeam,
                scoreAwayTeam: resp.score.fullTime.awayTeam,             
            });
            return matchObject;
        });
     

        // const match = new Match({
        //     leagueName: 'Bundes'
        // });

        try {
            console.log(match);
            await match.save();
            //res.status(201).json(match); 
        } catch (e) {
            console.log('error');
            res.status(422).json({
                errors: e.errors
            }); 
        }
    }
}

module.exports = new MatchController();
代码语言:javascript
复制
    const getDataForSheduleCJS = () => {
            fetch(`https://api.football-data.org/v2/competitions/PL/matches`, {
                headers: {
                  'Content-Type': 'application/json',
                  'X-Auth-Token': personalToken
            }}).then(resp => resp.json())
            // .then(data => data)
            .catch((error) => {
                alert("Wystąpił problem z danymi")
                console.error('Error:', error);
            });
        }
代码语言:javascript
复制
const express = require('express');
const router = new express.Router(); //zmieniamy nazwy z app.get na router.get
const MatchController = require('../controllers/match-controller');

router.get('/matches', MatchController.showMatches);
router.post('/matches', MatchController.create);

module.exports = router;
EN

回答 1

Stack Overflow用户

发布于 2021-11-17 12:16:55

此接口中请求用于从前端获取正文数据或查询参数例如您正在向后端发送post请求中的某些数据,在后端接口req.body中包含前端发送的对象u例如您要创建一个新用户,并且您正在向后端接口发送用户名和密码此请求中包含对象

代码语言:javascript
复制
{
  name:'Some Name',
  password:'somePassword'
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70004172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档