我在vanilla JS中编写了一个简单的函数fetch来从api获取te数据。我想使用node js将这些数据发送到我的数据库mongodb。我知道这段代码很混乱,但我的朋友在后台工作,我在前端工作,我们正在尝试合并这些代码。我不知道如何处理create function中的'req‘参数。谢谢你的帮助。
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(); 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);
});
}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;发布于 2021-11-17 12:16:55
此接口中请求用于从前端获取正文数据或查询参数例如您正在向后端发送post请求中的某些数据,在后端接口req.body中包含前端发送的对象u例如您要创建一个新用户,并且您正在向后端接口发送用户名和密码此请求中包含对象
{
name:'Some Name',
password:'somePassword'
} https://stackoverflow.com/questions/70004172
复制相似问题