使用json-server POST 数据结果只有id

使用json-server作为数据提供源

fetch('http://localhost:3000/user', {
            method: 'POST',
            body: JSON.stringify({name:name.value, age:age.value, gender:gender.value}),
                headers: {
                    'Cotent-Type': 'application/json'
                }
            })
            .then(res => res.json())
            .then(res => {
                if (res.id) {
                    alert('添加用户成功');
                    this.setState({name: '', age: 0, gender: ''});
                } else {
                    alert('添加失败');
                }
            })
            .catch(err => console.error(err));

结果只添加了一个

  {
    "id": 10002
  }

network里发送了两个请求,一个是OPTION请求,请问这个请求是做什么用的?
第二个请求是post请求,包含了要添加的数据,可是json文件里只有一个id信息,求解

阅读 5.8k
5 个回答

fetch方法发送的两个请求分别是

第一个post过去method里的方法,比如你可以把method: 'POST'改成method: 'PUT',post过去就是PUT这些配置信息

第二个就是i发送请求了,json文件只有id信息?是后台设置问题吧?

新手上路,请多包涵

请问有解决吗,也遇到这个问题

请求头里设置这个 Content-Type: application/json,

const request = async (url, options) => {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json'
    }
  })
  const data = await response.json()
  return { data }
}

export const create = (url, body) => {
  // Format Date moment(Date.now()).format("YYYY-MM-DD HH:mm:ss") //"2017-05-25 22:23:07"
  return request(url, {
    method: 'POST',
    body: JSON.stringify({ ...body, created_at: Date.now(), updated_at: Date.now() })
  })
}
新手上路,请多包涵

export function patch(id, values) {
return request(/api/users/${id}, {

method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),

});
}

export function create(values) {
return request('/api/users', {

method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),

});
}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题