我是React JS的新手。 我的问题是当我在React端使用axios.put方法时: 这是我的React组件中的一种方法:
commitAssign() {
let memberIds = this.state.assignedList;
// update the data
const headers = {
"Content-Type": "application/json"
};
axios
.put(`/api/projects/${this.props.project._id}`, { memberIds }, headers)
.then(res => {
this.state.assignedList = [];
this.props.onUpdate();
})
.catch(err => console.log(err));
}
这是我的快递路线:
app.put('/api/projects/:id',(req, res) => {
//update database
res.redirect(`/api/projects/${projectId}`);
})
当我运行react时,它看起来像这样:
好像axios.put向服务器发出多个请求,然后得到一个错误。 而且,我输入的数据仍然多次保存在数据库中(相同的数据)。
请注意,如果我将PUT方法更改为POST,那么一切都很好-没问题。而且我已经使用POSTMAN测试了服务器,这也没有问题。
有人知道在使用PUT方法时出现了什么问题吗?
我正在使用: 服务器依赖项: “ body-parser”:“ ^ 1.18.3”, “ cors”:“ ^ 2.8.4”, “表达”:“ ^ 4.16.3”, “猫鼬”:“ ^ 5.2.6” 客户端依赖项:
"dependencies": {
"axios": "^0.18.0",
"jquery": "^3.3.1",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"semantic-ui-css": "^2.3.3",
"semantic-ui-react": "^0.82.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^1.0.0",
"file-loader": "^1.1.11",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"webpack": "^4.16.4",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
编辑: 这是我的服务器:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');
var app = express();
app.use(cors());
mongoose.connect('mongodb://localhost:27017/teamApp_V1', {
useNewUrlParser: true
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/api/projects', (req, res) => {
Project.find((err, allProjects) => {
if (err || allProjects == null) {
console.log(err);
} else {
res.json(allProjects);
}
});
});
//creact new project
app.post('/api/projects', (req, res) => {
let newProject = req.body.newProject;
Project.create(newProject, (err, newProject) => {
if (err) {
console.log(err);
}
res.redirect('/api/projects');
});
});
//show
app.get('/api/projects/:id', (req, res) => {
let id = req.params.id;
Project.findById(id).populate('listMember').exec((err, foundProject) => {
if (err || foundProject == null) {
console.log(err);
res.redirect('/api/projects');
} else {
res.json(foundProject);
}
});
});
//edit project - assign member
app.put('/api/projects/:id', (req, res) => {
let projectId = req.params.id;
let memberIds = req.body.memberIds;
Project.findById(projectId, (err, foundProject) => {
if (err || foundProject == null) {
console.log(err);
res.redirect('/api/projects');
} else {
memberIds.forEach((memberId) => {
console.log(foundProject);
//update member id to project
foundProject.listMember.push(memberId);
//update project that this member is work for
Employee.findById(memberId, (err, foundMember) => {
if (err || foundMember == null) {
console.log(err);
res.redirect('/api/projects');
} else {
foundMember.project.push(foundProject._id);
foundMember.save();
}
})
})
foundProject.save((err) => {
if (err) {
console.log(err);
res.redirect('/api/projects');
} else {
res.redirect(`/api/projects/${projectId}`);
}
});
}
});
});
//delete project
// employees
//index employee
app.get('/api/employees', (req, res) => {
Employee.find().populate('project').exec((err, allEmployees) => {
if (err || allEmployees == null) {
console.log(err);
} else {
res.json(allEmployees);
}
});
});
//create new employee
app.post('/api/employees', (req, res) => {
let newEmployee = req.body.newEmployee;
Employee.create(newEmployee, (err, newEmployee) => {
if (err) {
console.log(err);
} else {
//do nothing
}
res.redirect('/api/employees');
})
});
//edit employee
app.get('*', (req, res) => {
res.send('Oops! Page is not found.');
});
app.listen(8081, process.env.IP, () => {
console.log('server is running');
});
答案 0 :(得分:0)
我认为问题是res.redirect('/api/projects');
。
您的服务器返回302,通知axios继续跟踪重定向并从中获取响应。这就是为什么会导致无限重定向循环的原因。
请将res.redirect
更改为res.status(400).json({ message: 'whatever' })
之类的内容。该API绝不应返回重定向,而应使用状态代码让客户端知道调用是否成功,并自行确定下一步要做什么。
您在客户端的catch
将捕获该错误并执行重定向或其他操作。
您可以查看https://en.wikipedia.org/wiki/List_of_HTTP_status_codes,以获取有关不同状态代码的参考。
答案 1 :(得分:0)
我相信Dat Tran的回答在大多数情况下都是正确的,但是它不包含代码,也没有告诉您采用哪种方法以及应该如何使用。
无论如何,这是由于重定向而发生的。您的代码会导致无限重定向循环,在chrome中如下所示:
发送错误/成功后,无需重定向,只需发送json,然后稍后在UI上接收到json时显示错误/成功的内容即可。
将方法更改为以下内容(请注意,我已经添加了注释):
app.put('/api/projects/:id', (req, res) => {
let projectId = req.params.id;
let memberIds = req.body.memberIds;
Project.findById(projectId, (err, foundProject) => {
if (err || foundProject == null) {
console.log(err);
res.json(err);
} else {
memberIds.forEach((memberId) => {
console.log(foundProject);
//update member id to project
foundProject.listMember.push(memberId);
//update project that this member is work for
Employee.findById(memberId, (err, foundMember) => {
if (err || foundMember == null) {
console.log(err);
res.json({ someError: err }); // send an error msg. <====
} else {
foundMember.project.push(foundProject._id);
foundMember.save();
}
})
})
foundProject.save((err) => {
if (err) {
console.log(err);
res.json(err); // just like you did in app.get <====
} else {
res.json(foundProject);
}
});
}
});
});