gpt4 book ai didi

javascript - 在 Express 中编写后端代码并连接到 React 时遇到问题

转载 作者:行者123 更新时间:2023-12-03 06:59:09 26 4
gpt4 key购买 nike

我正在编写用于在网站内创建组的代码。我使用 MongoDB 作为我的数据库,但作为初学者,我很难理解他们提供的 API。所以基本上,当我尝试为我的网站创建一个组时,我在将后端连接到前端时遇到了问题。这是 create_group 的后端代码

router.post('/create_group', (req, res) => {
try {
const newGroup = Group.create(req.body);

res.status(201).json({
data: {
Groups:
newGroup
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
//res.json(database.groups[database.groups.length-1]);
如您所见,我想编写一个适合 MongoDB 的代码,它看起来像我注释掉的部分。我想返回我刚刚保存的对象,以便在更改路线时可以显示该信息。前端代码如下所示:
 onSubmitCreate = () => {
fetch('http://localhost:3000/groups/create_group', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
members: 1,
likes: 0
})
})
.then(response => response.json())
.then(group => {
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);


}
});
}
在前端,当我请求将信息发布到数据库时,我想读取响应并使用该信息。但是当我 console.log 组变量时,我只是得到一个空对象作为响应,我不知道如何让它返回用户输入的信息。如果你想看看 onCreateGroup 功能是什么样的, 这里是。
    const onCreateGroup = (group) => {
setGroupInfo({
name: group.name,
description: group.description,
likes: 0,
members: 1
});
setRoute('group_page');
}
请帮我!先感谢您!
编辑:我被要求在我导入 express 的地方发布 js 文件,所以我在这里发布
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://teamboogle:wMKsYJNhTfL89k9@cluster0.nhcrc.mongodb.net/TalkWithMe?retryWrites=true&w=majority", { useNewUrlParser: true });

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const profileRouter = require('./routes/profile');
const postsRouter = require('./routes/posts');
const groupsRouter = require('./routes/groups');
const signinRouter = require('./routes/signin');
const registerRouter = require('./routes/signin');






var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

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

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/profile', profileRouter);
app.use('/posts', postsRouter);
app.use('/groups', groupsRouter);
app.use('/signin', signinRouter);
app.use('/register', registerRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});


const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function(){
console.log('Connection Secured');
})

module.exports = app;

最佳答案

您没有正确地将对象保存在 MongoDB 中,您还需要返回您保存在 Group 中的对象。收藏也是如此。
另外,既然你回来了 data.Groups.group ,您还需要在响应中阅读该内容
请试试这个:

router.post('/create_group', async (req, res) => {
try {
const newGroup = new Group(req.body);
let group = await newGroup.save()

res.status(201).json({
data: {
Groups:
group//return the saved object
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
}
在前端代码中
onSubmitCreate = () => {
fetch(...)
.then(response => response.json())
.then(data => {
// read data.Groups.group from response
let group = data.Groups.group
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);


}
});
}

关于javascript - 在 Express 中编写后端代码并连接到 React 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64830563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com