iT邦幫忙

0

Vue Axios 傳送post請求,回傳500的問題

大家好,
我想請問一下。
我是在專案裡使用json-server當作資料庫來測試,port修改為3020。
資料如下

//db.json
{
    "books": [
        {
          "name": "HappyTime",
          "description": "快樂時光"
        },
        {
          "name": "1984",
          "description": "1984"
        },
        {
          "name": "投資",
          "description": "save money"
        },
        {
          "name": "try try 看",
          "description": "試試看"
        },
        {
          "name": "###",
          "description": "###"
        },
        {
          "name": "!!",
          "description": "驚嘆"
        },
        {
          "name": "-jjJJ",
          "description": "大小寫"
        }
      ]
}

在使用axios.get時,沒有問題

//成功
const getAxios = function(){
    axios.get('http://localhost:3020/books')
    .then((res)=>{
        return getBooks.value = res.data
    })
    .catch((error)=>{
        console.log('獲取失敗');
    })
}

但當想要上傳資料時,就會出錯

//失敗
const bookName=ref() //跟input v-model綁定在一起
const bookDescription= ref() //跟input v-model綁定在一起

const addForm =function(){
    axios.post('http://localhost:3020/books',{
        name:bookName.value,
        description:bookDescription.value
    }).then((res)=>{
        console.log('新增成功');
    }).catch((error)=>{
        console.log('新增失敗');
    })
}

回傳的錯誤訊息是:POST http://localhost:3020/books 500 (Internal Server Error)

我去查一下,好像是資料格式的問題?
將資料修改成json也是回報錯誤500

const bookName=ref()
const bookDescription= ref()
//還是失敗
const addForm =function(){
     let sentData = JSON.stringify({
        name:bookName.value,
        description:bookDescription.value
    });
    axios.post('http://localhost:3020/books',sentData).then((res)=>{
        console.log('新增成功');
    }).catch((error)=>{
        console.log('新增失敗');
    })
}

這要怎麼解決?感謝

froce iT邦大師 1 級 ‧ 2021-11-05 10:20:53 檢舉
500是內部伺服器錯誤,表示是你的後端有問題。
並不一定是你JSON搞錯格式之類的。

要除錯請去看你後端的log
greenriver iT邦研究生 5 級 ‧ 2021-11-05 11:07:11 檢舉
謝謝幫忙。
發現是db.json少給了id
"books": [
{
"id": 0,
"name": "HappyTime",
"description": "快樂時光"
},
{
"id": 1,
"name": "1984",
"description": "1984"
}
]
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-11-05 10:26:29
最佳解答

參考這篇試試看

//大概像這樣
const obj = { name:"The Martian", description:"Science fiction" }
axios.post("http://localhost:3020/books",obj).then( res => { ... })
greenriver iT邦研究生 5 級 ‧ 2021-11-05 11:08:27 檢舉

謝謝幫忙。
發現是db.json少給了id....

"books": [
    {
        "id": 0,
        "name": "HappyTime",
        "description": "快樂時光"
    },
    {
        "id": 1,
        "name": "1984",
        "description": "1984"
    }
]

我要發表回答

立即登入回答