尝试使用 axios 从 Reactjs 组件发送数据以表达应用程序

我正在开发一个项目,前端使用 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 setup

app.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 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 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;


有只小跳蛙
浏览 94回答 1
1回答

偶然的你

当您从客户端发送 post 请求时,它将位于 req 对象的 body 属性中const router = express.Router(); // you shoud listen post requestrouter.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});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript