我正在尝试使用 react 和 django rest 框架来制作评论功能,只有经过身份验证的用户才能对博客发表评论。我可以使用 Postman 实现相同的目标,但是当我尝试使用 react 应用程序中的 axios 时它不起作用。尽管用户已登录,但它显示未提供经过身份验证的详细信息。
这是我到目前为止使用 axios 所做的
export const blogPrimaryCommentCreate = (type, slug, content) => (dispatch, getState) => {
var bodyFormData = new FormData();
bodyFormData.append('content', content);
axios
.post(`http://127.0.0.1:8000/api/comments/create/`, bodyFormData, { params: { type, slug } }, tokenConfig(getState))
.then(res => {
dispatch(createMessage({ commentSuccess: 'Thank You. Comment has been submited to Moderator' }));
dispatch({
type: CREATE_BLOG_PRIMARY_COMMENT,
payload: res.data
});
})
.catch(err =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
export const tokenConfig = getState => {
// Get token from state
const token = getState().auth.token;
// Headers
const config = {
headers: {
"Content-Type": "application/json"
}
};
// If token, add to headers config
if (token) {
config.headers["Authorization"] = `Token ${token}`;
}
return config;
};
这是来自网络选项卡下的 Chrome Dev 工具的错误详细信息
##General##
Request URL: http://127.0.0.1:8000/api/comments/create/?type=articles&slug=my-second-blog-my-second-blog-my-second-blog-my-se
Request Method: POST
Status Code: 401 Unauthorized
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
##Response Header##
Access-Control-Allow-Origin: *
Allow: POST, OPTIONS
Content-Length: 58
Content-Type: application/json
Date: Fri, 06 Sep 2019 20:27:34 GMT
Server: WSGIServer/0.2 CPython/3.7.1
Vary: Accept, Cookie, Origin
WWW-Authenticate: Token
X-Frame-Options: SAMEORIGIN
##Request Header##
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary4Ex7moZAQ1BAIDFT
DNT: 1
Origin: http://localhost:3000
Referer: http://localhost:3000/blogs/my-second-blog-my-second-blog-my-second-blog-my-se
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Mobile Safari/537.36
type: articles
##Query String Parameter##
slug: my-second-blog-my-second-blog-my-second-blog-my-se
content: dfg
##Form Data##
Test
您将标题作为第四个参数传递,但它是params
.
这是方法签名: axios#post(url[, data[, config]])
只需将您的请求更新为:
axios.post(URL, bodyFormData, { params: { type, slug }, ...tokenConfig(getState) })
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句