【问题标题】:How to use ajax from react to express?如何使用 ajax 从 react 到 express?
【发布时间】:2019-04-11 03:43:05
【问题描述】:

我是使用 react 的新人。现在我必须解决一个问题。 到目前为止,我通过 express 和客户端通过 react 包括 react router 和 redux,redux-thunk 来制作服务器端部分。当我通过 axios 将帖子发送到 express 服务器时,会出现以下错误

POST http://localhost:8080/api/users 404(未找到)

如何在 express 中接受 redux-thunk 的 CRUD 请求?

服务器端代码如下

//app.js
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('/api/users', userRouter);
app.use('/profile', profileRouter);

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


//react redux-thunk side is
axios.post('/api/users', { name: 'LNI' });

【问题讨论】:

    标签: ajax rest axios crud redux-thunk


    【解决方案1】:

    您不必提供/public 而只是使用public。 路径生成由path 模块本身管理。

    app.use(express.static(path.join(__dirname, 'public')));
    

    表达POST请求是这样处理的

    app.post('/api/users', userRouter);
    

    从官方快递文档中阅读更多关于路由的信息 - https://expressjs.com/en/guide/routing.html

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 2016-11-01
      • 2020-07-02
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2023-03-11
      • 2016-07-23
      • 2021-06-30
      相关资源
      最近更新 更多