使用content-header application / x-www-form-urlencoded提交表单会收到404错误,但在Postman中工作正常

时间:2017-06-18 07:19:18

标签: javascript reactjs express post

我正在构建一个登录页面,其中React处理前端,Express,后端。当我单击“提交”时,它将在控制台中返回错误:

POST http://localhost:8000/auth/login 404(未找到)

但是当我使用postman来测试发布到/ auth / login时它是成功的。在processForm函数中,我尝试使用我编写的帖子来获取不同的api以查看它是否是前端问题并且它返回422错误(如预期的那样)所以我猜它是后端问题但是我我不确定是什么问题。

这是我用来处理表单的反应组件中的函数:

  processForm(e) {
    e.preventDefault();

    const email = encodeURIComponent(this.state.user.email);
    const password = encodeURIComponent(this.state.user.password);
    const formData = `email=${email}&password=${password}`;

    fetch('/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: formData
    }).then(response => {
      if (response.ok) {
        response.json().then(() => {
          this.setState({
            errors: {}
          });
          console.log('The form is valid');
        })
      } else {
        response.json().then(error => {
          const errors = error ? error : {};
          errors.message = error.message;
          this.setState({
            errors
          });
        });
      }
    }).catch(err => {
      console.log(err);
    });
  }

我是如何用快速路由器处理后端的:

router.post('/login', (req, res) => {
  const validationResult = validateLoginForm(req.body);
  if (!validationResult.success) {
    res.status(400).json({
      success: false,
      message: validationResult.message,
      errors: validationResult.errors,
    });
  }
  res.status(200).end();
});

以及在server.js中安装路由的相关代码:

import AuthRoutes from './routes/auth';

app.use(bodyParser.urlencoded({ extended: false }));

app.use('/auth', AuthRoutes);

0 个答案:

没有答案