我正在尝试使用axios将数据从redux-form发布到api服务器。我发布数据的动作创建者如下所示:
//Action creator for submitting edited post
export function submitEditedPost(values, callback) {
const request = axios.post(`${API}/posts`, {headers}, {values});
return dispatch => {
return request.then((data) => {
callback();
console.log(data)
dispatch({
type:SUBMIT_POST,
payload: data
})
})
}
}
我调用action-creator的形式的onSubmit()
方法如下:
onSubmit(values) {
var id = Math.random().toString(36).substr(-8);
var d = new Date().toLocaleTimeString();
const formData = {};
for (const field in this.refs) {
formData[field] = this.refs[field].value;
}
formData.id = id;
formData.timestamp = d;
console.log('-->', formData);
this.props.submitEditedPost(formData, () => {
this.props.history.push('/');
});
}
当我尝试console.log编辑的值时,我可以正确地看到它,但我无法发布编辑的值并更新api。错误消息显示在下面的屏幕截图中:
我该怎么办?有人可以帮我解决这个问题吗?
编辑1:我的整个操作文件:
import axios from 'axios';
export const FETCH_POSTS = 'fetch_posts';
export const CREATE_POST = 'create_post';
export const FETCH_POST = 'fetch_post';
export const DELETE_POST ='delete_post';
export const EDIT_POST = 'edit_post';
export const SUBMIT_POST = 'submit_post';
let token ;
if(!token)
token = localStorage.token = Math.random().toString(36).substr(-8)
const API = 'http://localhost:3001';
const headers = {
'Accept' : 'application/json',
'Authorization' :'token'
}
//Action creator for fetching posts from the API server
export function fetchPosts() {
const URL = `${API}/posts`;
const request = axios.get(URL,{headers});
return dispatch => {
return request.then(({data}) => {
console.log(data);
dispatch({
type : FETCH_POSTS,
payload : data
})
})
}
}
//Action Creator for creating posts
export function createPosts(values, callback) {
return dispatch => {
return axios.post(`${API}/posts`,values,{headers})
.then((data) => {
callback();
console.log(data)
dispatch({
type: CREATE_POST,
payload: data
})
})
}
}
//Action Creator for displaying a selected post
export function fetchPost(id) {
const request = axios.get(`${API}/posts/${id}`,{headers});
return dispatch => {
return request.then(({data}) => {
console.log(data);
dispatch({
type: FETCH_POST,
payload: data
})
})
}
}
//Action creator for deleting post
export function deletePost(id, callback) {
const request = axios.delete(`${API}/posts/${id}`, {headers})
.then(() => callback());
return {
type: DELETE_POST,
payload: id
}
}
//Action creator for editing post
export function editPost(id, callback) {
const request = axios.get(`${API}/posts/${id}`,{headers});
return dispatch => {
return request.then((data) => {
callback();
console.log(data);
dispatch({
type: EDIT_POST,
payload: data
})
})
}
}
//Action creator for submitting edited post
export function submitEditedPost(id, values, callback) {
console.log(values, 'values')
console.log(id, 'id')
const request = axios.put(`${API}/posts/${id}`, {values}, {headers});
return dispatch => {
return request.then((res) => {
callback();
console.log("response", res)
dispatch({
type:SUBMIT_POST,
payload: res
})
})
}
}