Node JS无响应(猫鼬)

时间:2018-07-21 11:13:19

标签: javascript node.js reactjs mongoose axios

我通过以下方式从React发送request

export const loadItems = () => async dispatch => {
  await axios
    .get("http://localhost:8000/api/users")
    .then(response => {
      console.log(response.users);
      dispatch(dataLoaded(response.users));
    })
    .catch(err => {
      dispatch(dataLoadFailed(err));
    });
};

但是没有response,并且服务器没有使用request,这是我的服务器应用代码:

server.js

// a lot of requires
const todoRoutes = require("./routes/serverRoute");
const url = "mongodb://localhost:27017/taskManager";
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect(
  url,
  { useNewUrlParser: true },
  function(err) {
    if (err) {
      console.log(err);
    } else console.log("Database connected");
  }
);

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "/public/index.html"));
});

// cors allow
app.use("/api", todoRoutes);

app.listen(8000, () => {
  console.log("API started");
});

这是我使用的控制器,对于Schema和DB来说都很好,我检查了从节点到控制台的输出,users已定义并包含数据

const mongoose = require("mongoose");
const User = require("../models/UserModel");

module.exports = {
  getUsers(req, res) {
    User.find().exec((err, users) => {
      if (err) {
        console.log(err);
        return res.send({ err });
      } else {
        console.log(users);
        return res.send({ users });
      }
    });
  }
};

这是我的路由器:

module.exports = router => {
  router.get('/users', userController.getUsers);
}

1 个答案:

答案 0 :(得分:0)

好的,我自己买的。问题在这里:

router.get('/users', userController.getUsers);

应该是这样的:

router.get('/users', userController.getUsers());