【问题标题】:Empty response from post with formData来自带有 formData 的帖子的空响应
【发布时间】:2018-04-26 12:41:13
【问题描述】:

在 VueJS 中我正在尝试发布帖子

let data = new FormData()
data.append('name', 'hey')

fetch('http://homestead.test/api/customers', {
    method: 'POST',
    headers: {
        'Content-type': 'multipart/form-data'
    },
    body: data
})
.then((response) => response.json())
.then((response) => {
    console.log(response)
})

添加了资源路由

Route::resource('customers', 'CustomerController');

并返回请求

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    return $request->all();
}

我的 console.log 打印以下内容

[]

【问题讨论】:

    标签: laravel vue.js fetch form-data


    【解决方案1】:

    您在 fetch 的 then 之后调用 then 不存在。

    此时您可以使用箭头函数来访问您从请求中获得的响应变量

    let data = new FormData()
    data.append('name', 'hey')
    
    fetch('http://homestead.test/api/customers', {
        method: 'POST',
        headers: {
            'Content-type': 'multipart/form-data'
        },
        body: data
    })
    .then((response) => {
      // now you can access response here
      console.log(response)
    })
    

    【讨论】:

    • 它给了我一个Promise {<pending>} 回复
    • 我的错,应该是现在。如果要打印为 json,可以使用 JSON.parse。
    • 这个问题的承诺是错误的。我猜它只是正确的。
    【解决方案2】:

    我不明白为什么 FormData 为空,但所有带有 JSON 正文的请求都有效。

    let data = new FormData() 
    data.append('name', 'hey')
    
    let json = JSON.stringify(Object.fromEntries(data));;
    fetch('http://homestead.test/api/customers', {
        method: 'POST',
        headers: {
            'Content-type': 'application/json'
        },
        body: data
    })
    .then((response) => response.json())
    .then((response) => {
        console.log(response)
    })
    

    【讨论】:

      【解决方案3】:

      我认为问题可能在于它应该使用的内容标题类型

      {
          Content-type: 'application/json'
      }
      

      并尝试使用以下方式发送数据:

      body :JSON.stringify(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 2022-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多