Axios发布请求
// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
dispatch(clearErrors());
const image = new FormData();
image.append("avatar", avatar, avatar.name);
axios
.post("/api/profile", image, profileData)
.then(res => history.push("/dashboard"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
编辑---> Axios发布请求第二次尝试
// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
dispatch(clearErrors());
const image = new FormData();
image.append("avatar", avatar, avatar.name);
image.append("user", profileData, profileData.username);
axios
.post("/api/profile", image)
.then(res => history.push("/dashboard"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
profileData
是我在req.body
中想要的,而化身是我在req.file
中通过穆勒在后端获得的,但是我收到的是req.file
req.body
(只是一个空对象)中没有图片
这是我在节点中的路由器
router.post(
"/",
upload.single("avatar"),
passport.authenticate("jwt", { session: false }),
(req, res) => {
console.log(req.body);
}
);
答案 0 :(得分:0)
我认为您的路线在路线文件中为/api/profile
。
您没有显示标题profileData
。
应该是这样
const profileData = {
headers: { 'content-type': 'multipart/form-data' }
}
然后,您可以像已经进行的那样向服务器请求。
答案 1 :(得分:0)
尝试使用FormData通过以下方式实现
handleSubmit(e)
{
e.preventDefault();
const err = this.validate();
if(!err)
{
var formData = {
category:this.state.category,
course:this.state.course,
};
const {category,course} = this.state;
let fd = new FormData();
fd.append('Test',this.state.testFile,this.state.testFile.name);
fd.append('category',category);
fd.append('course',course);
console.log(fd);
axios({
method: 'post',
url: 'http://localhost:7777/api/uploadTest',
data: fd,
})
.then((response) => {
if(response.data=='Success')
{
alert('Test has been Added..!!');
}
else
{
alert('Something went wrong');
this.setState({category:''});
}
// this.setState({success:'Alert: '+response.data});
})
.catch((e) =>
{
console.error(e);
this.setState({success:'Alert: Something went wrong'});
});
}
}