gpt4 book ai didi

reactjs - axios 发布错误

转载 作者:行者123 更新时间:2023-12-05 07:41:06 26 4
gpt4 key购买 nike

我试图发布到我的 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();
});

最佳答案

您可以将 mongoose 查询更改为,

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

关于reactjs - axios 发布错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com