我正在开发一个项目,前端使用 ReactJS typescript,后端使用 express,数据库使用 MongoDB。我遇到的主要问题是我想以某种方式将数据从我的 React 组件发送到 express 应用程序,以便它可以查询并将内容添加到数据库中。目前,我在 http://localhost:9000 上运行 express 服务器,在 http://localhost:3000 上运行 React 应用程序,我可以使用路由连接它们。我的快递应用如下所示:var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');var cors = require('cors');var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');var testAPIRouter = require('./routes/testAPI');var testAddUser = require('./routes/addUser');const MongoClient = require('mongodb').MongoClient;const mongoose = require('mongoose');var app = express();// view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'jade');app.use(cors());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('/', indexRouter);app.use('/users', usersRouter);app.use("/testAPI", testAPIRouter);app.use("/addUser", testAddUser);// catch 404 and forward to error handlerapp.use(function(req, res, next) { next(createError(404));});// error handlerapp.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 dbRoute = 'mongodb+srv://Adminname:fjfeinjd@pawornaw-b4vzg.gcp.mongodb.net/test?retryWrites=true&w=majority';mongoose.connect(dbRoute, {useNewUrlParser: true}) .then(() => console.log("Connected to MongoDB")) .catch(err => console.error("Could not connected to Mongo"));module.exports = app;
1 回答
偶然的你
TA贡献1841条经验 获得超3个赞
当您从客户端发送 post 请求时,它将位于 req 对象的 body 属性中
const router = express.Router();
// you shoud listen post request
router.post('/', function(req, res) {
const { body } = req;
// do somethin with data which you recieved in body, save to database for example
// and send response to the client
res.json({ message: 'your data was saved'});
});
module.exports = router;
将数据发送给客户端使用:
router.get('/', function(req, res) {
res.json({ data: 'Some data'}); // or res.send('some text') to send plain text
});
添加回答
举报
0/150
提交
取消