反应 - JS |传递主体变量名称而不是其内容
React - JS | Passing body variable name rather than its content
我想我有一个很好的问题。我正在制作我自己的总体请求存储库,我可以参考它而不是将所有请求嵌入到每个单独的 JS 文件中。
对于传递正文的请求,我需要将两件事传递到 stringify
- 标识符表示字段
- 值表示内容
我似乎无法用其实际内容替换标识符字段,我认为它传递的是“字段”作为其名称而不是“字段”字符串的内容。
调用代码:
Request.Request.useSendPostWithBody("User/checkAlt","email","XXX@XXX.uk")
请求代码:
Request.useSendPostWithBody = (endpoint, field, content) => {
const [ data, setData ]=useState('')
useEffect(() => {
fetch(`${window.ipAddress.ip}/${endpoint}`, {
method: "POST",
headers:{'Content-Type':'application/json'},
body: JSON.stringify({ email: content })}) // this works as the required field for this request is email
// body: JSON.stringify({ field : content })}) // this doesn't and here is where I think the issue lies because not all requests are going to pass "email"
.then((result)=> { return result.json() })
.catch(error =>{
console.log("error")
})
.then((data)=>{ setData(data)
console.log('data')
console.log(data) })
},[])
}
你需要使用方括号[]
来表示键名需要被评估,像这样:
{
// other values,
body: JSON.stringify({ [field]: content })}),
}
我想我有一个很好的问题。我正在制作我自己的总体请求存储库,我可以参考它而不是将所有请求嵌入到每个单独的 JS 文件中。
对于传递正文的请求,我需要将两件事传递到 stringify
- 标识符表示字段
- 值表示内容
我似乎无法用其实际内容替换标识符字段,我认为它传递的是“字段”作为其名称而不是“字段”字符串的内容。
调用代码:
Request.Request.useSendPostWithBody("User/checkAlt","email","XXX@XXX.uk")
请求代码:
Request.useSendPostWithBody = (endpoint, field, content) => {
const [ data, setData ]=useState('')
useEffect(() => {
fetch(`${window.ipAddress.ip}/${endpoint}`, {
method: "POST",
headers:{'Content-Type':'application/json'},
body: JSON.stringify({ email: content })}) // this works as the required field for this request is email
// body: JSON.stringify({ field : content })}) // this doesn't and here is where I think the issue lies because not all requests are going to pass "email"
.then((result)=> { return result.json() })
.catch(error =>{
console.log("error")
})
.then((data)=>{ setData(data)
console.log('data')
console.log(data) })
},[])
}
你需要使用方括号[]
来表示键名需要被评估,像这样:
{
// other values,
body: JSON.stringify({ [field]: content })}),
}