我正在使用 fetch 调用 PSQL POST 查询。查询在 postgres 中正常运行,但在通过 vscode 运行时返回 404 not found 错误。 这是我的代码:
async function onCreateTag(){
const body = {tagName, selectedTagColor}
if (tagName !== undefined){
const res = await callCreateTag(`http://localhost:4000/createtag/${username}`, "POST",body).then((res)=>handleFinishCreateTag(res.json()))
console.log(res)
}
}
callCreateTag 是我做的custom hook的一个函数,和'callAPI'一样:
import {useState,useEffect} from 'react'
const useAPICallBody=()=>{
const [res, setRes] = useState()
async function callAPI(url, method, body){
console.log(url)
console.log(body)
await fetch(url,
{method:method,
headers:{"Content-Type":"application/json"},
body:JSON.stringify(body)
}).then((response)=>response.json()).then((json)=>setRes(json))
}
return {res, callAPI}
}
export default useAPICallBody;
这是我的API调用代码:
app.post('/api/createtag/:username', async(req,res)=>{
try {
const {username} = req.params
const {tagName, selectedTagColor} = req.body
const response = await pool.query(
"INSERT INTO tags (username, tag, tagcolor) VALUES ($1, $2, $3)",[username, tagName, selectedTagColor]
)
console.log(response)
res.json(response.rows)
} catch (error) {
console.error(error.message)
}
})