2017-08-09 9 views
1

、私はエラーを取得する:Axiosのポストエラー

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://d[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}`); 
}); 

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

私はこの問題を考えますあなたのnodejsバックエンドから来ます。 nodejsコードを共有できますか? – Nevosis

+0

@Nevosis更新された質問 – Bomber

+0

あなたの要求にheader(Content-Type:application/json)を付けてみましたか? –

答えて

0

あなたは

let query = {} //or any other query 
User.find(query,function(err,res){ 
... 
}) 
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