Axios发布错误

时间:2017-08-09 09:31:11

标签: reactjs axios

我想发布到我的api endpint,我收到错误:

Uncaught (in promise) Error: Network Error
    at createError (C:\sites\LYD\node_modules\axios\lib\core\createError.js:16)
    at XMLHttpRequest.handleError (C:\sites\LYD\node_modules\axios\lib\adapters\xhr.js:87)

我的axios帖子是:

submitForm(UserDetails) {
let self = this;
self.show();

axios
    .post('http://localhost:3001/api/users', UserDetails)
    .then(function(response) {
        self.hide();
    });
}

我的节点错误是:

C:\sites\LYD>node server
api running on port 3001
(node:11808) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: First argument must be a string or Buffer
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:555:11)
    at C:\sites\LYD\server\index.js:75:20
    at C:\sites\LYD\node_modules\mongoose\lib\model.js:3809:16
    at C:\sites\LYD\node_modules\mongoose\lib\services\model\applyHooks.js:164:17
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

有什么想法吗?

我的server.js是:

//first we import our dependencies...
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('../models/users');

//and create our instances
const app = express();
const router = express.Router();

//set our port to either a predetermined port number if you have set it up, or 3001
const port = process.env.API_PORT || 3001;

//db config -- REPLACE USERNAME/PASSWORD/DATABASE WITH YOUR OWN FROM MLAB!
const mongoDB =
  'mongodb://dxxx@aws-eu-west-1-portal.4.dblayer.com:10204/xxx?ssl=true';
mongoose.connect(mongoDB, { useMongoClient: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

//now we should configure the APi to use bodyParser and look for JSON data in the body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader(
    'Access-Control-Allow-Methods',
    'GET,HEAD,OPTIONS,POST,PUT,DELETE'
  );
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  //and remove cacheing so we get the most recent comments
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

//now  we can set the route path & initialize the API
router.get('/', function(req, res) {
  res.json({ message: 'API Initialized!' });
});

//adding the /comments route to our /api router
router
  .route('/users')
  //retrieve all comments from the database
  .get(function(req, res) {
    //looks at our Comment Schema
    User.find(function(err, users) {
      if (err) res.send(err);
      //responds with a json object of our database comments.
      res.json(users);
    });
  })
  //post new comment to the database
  .post(function(req, res) {
    var NewUser = new User();

    req.body.accessCode ? (NewUser.accessCode = req.body.accessCode) : null;
    req.body.age ? (NewUser.age = req.body.age) : null;
    req.body.drinkConcern
      ? (NewUser.drinkConcern = req.body.drinkConcern)
      : null;
    req.body.drinkOften ? (NewUser.drinkOften = req.body.drinkOften) : null;
    req.body.ethnicity ? (NewUser.ethnicity = req.body.ethnicity) : null;
    req.body.gender ? (NewUser.age = req.body.gender) : null;
    req.body.language ? (NewUser.language = req.body.language) : null;

    NewUser.save(function(err) {
      if (err) res.end(err);

      res.json({ message: 'Comment successfully added!' });
    });
  });

//Adding a route to a specific comment based on the database ID
router
  .route('/users/:id')
  //The put method gives us the chance to update our comment based on the ID passed to the route
  .put(function(req, res) {
    Comment.findById(req.params.id, function(err, user) {
      if (err) res.send(err);
      //setting the new author and text to whatever was changed. If nothing was changed
      // we will not alter the field.
      req.body.author ? (comment.author = req.body.author) : null;
      req.body.text ? (comment.text = req.body.text) : null;
      //save comment
      user.save(function(err) {
        if (err) res.send(err);
        res.json({ message: 'Comment has been updated' });
      });
    });
  })
  //delete method for removing a comment from our database
  .delete(function(req, res) {
    //selects the comment by its ID, then removes it.
    User.remove({ _id: req.params.comment_id }, function(err, user) {
      if (err) res.send(err);
      res.json({ message: 'Comment has been deleted' });
    });
  });

//Use our router configuration when we call /api
app.use('/api', router);

//starts the server and listens for requests
app.listen(port, function() {
  console.log(`api running on port ${port}`);
});

我已将我的axios帖子更改为:

let self = this;
    self.show();
    const headers = {
        'Content-Type': 'application/json',
    };
    axios
        .post('http://localhost:3001/api/users', UserDetails, headers)
        .then(function(response) {
            self.hide();
        });

2 个答案:

答案 0 :(得分:0)

您可以将mongoose查询更改为

let query = {} //or any other query
User.find(query,function(err,res){
...
})

答案 1 :(得分:0)

我认为问题出在您的路线上。 当您创建路线而不是使用router.route('/route').post(function(req, res) { ... }时,请使用router.post('/route', function(req, res) { .... }(显然将.post更改为您要使用的方法)

在您的代码中,这将是:

router
  .get('/users', function(req, res) {
    User.find(function(err, users) {
      if (err) res.send(err);
      res.json(users);
    });
})

我认为您只能app.route('/route').get(...).post(...)而不能router

查看快速路由文档以获取更多信息:https://expressjs.com/en/guide/routing.html