无法POST ajax请求

时间:2017-07-09 07:17:08

标签: ajax reactjs

任何人都可以向我解释为什么我不能发布ajax请求。当我运行此代码时,控制台显示POST http://localhost:8080/api/users 404(未找到),并且在networth部分中预览未找到404 在index.js文件中

        var path = require('path');
    var express = require('express');
    var webpack = require('webpack');
    var config = require('./webpack.config.dev.js');

    var app = express();
    var compiler = webpack(config);
    var bodyParser = require('body-parser');
    var users = require('./server/routes/users');

    app.use(bodyParser.json());

    app.use('/api/users', users);

    app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.publicPath
    }));

    app.use(require('webpack-hot-middleware')(compiler));

    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'index.html'));
    });

    app.listen(8080, 'localhost', function(err) {
      if (err) {
        console.log(err);
        return;
      }

      console.log('Listening at http://localhost:8080');
    });

和用户文件

    var express = require('express')
    var router = express.Router()

    // middleware that is specific to this router
    function validateInput(data) {
      let errors = {};

      if (Validator.isNull(data.username)){
        errors.username = "This field is required";
      }
      if (Validator.isEmail(data.email)) {
        errors.email = "Email is invalid";
      }
      if (Validator.isNull(data.password)){
        errors.password = 'This field is required';
      }
      if (Validator.isNull(data.passwordConfirmation)){
        errors.passwordConfirmation = 'This field is required';
      }
      if (Validator.equals(data.password, data.passwordConfirmation)){
        errors.passwordConfirmation = 'Password must match';
      }
      return {
        errors,
        isValid: isEmpty(errors)
      }
    }

    router.post('/api/users', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });

    module.exports = router

1 个答案:

答案 0 :(得分:1)

users.js文件中该函数应为

router.post('/', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });

由于此index.js已在请求网址/api/users中解决http://localhost:8080/api/users部分。因此,您只需在/api/users js文件中的users之后进行映射。

例如,如果您在users.js文件中有以下功能

router.post('/:id', (req, res) => {
      ...
    }

它将转到路径http://localhost:8080/api/users/1

修改 在您现有的版本中,

router.post('/api/users', (req, res) => {
  ...
}

将解析为http://localhost:8080/api/users/api/users