2017-08-09 3 views
1

ich meine api endpint zu schreiben versuche, erhalte ich die Fehlermeldung:Axios Beitrag Fehler

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) 

Mein axios Beitrag ist:

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

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

Mein Knoten Fehler ist:

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) 

Irgendwelche Ideen?

Mein server.js ist:

//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://[email protected]: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}`); 
}); 

Ich habe meine axios geändert zu diesem Beitrag:

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(); 
     }); 
+0

denke ich das Problem, kommen von Ihrem Nodejs Backend. Können Sie den nodejs-Code teilen? – Nevosis

+0

@Nequisis aktualisierte Frage, danke – Bomber

+0

haben Sie versucht, Header (Content-Type: application/json) an Ihre Anfrage anfügen? –

Antwort

0

Sie können die Mungo Abfrage ändern,

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

Ich denke, Das Problem liegt bei deinen Routen. Wenn Sie eine Route anstelle der Verwendung router.route('/route').post(function(req, res) { ... } zu erstellen, verwenden router.post('/route', function(req, res) { .... } In Ihrem Code

(natürlich .post auf die Methode, die Sie verwenden möchten, ändern) dies wäre:

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

Ich glaube, Sie nur app.route('/route').get(...).post(...) tun können aber nicht mit router

Blick auf die Express-Routing-Dokumentation für weitere Informationen: https://expressjs.com/en/guide/routing.html