【发布时间】:2022-01-11 03:43:39
【问题描述】:
之前有人问过这个问题,但问题没有解决发送方法,标记的解决方案对我不起作用。
我试图在后端的 JSON 对象中获取布尔值,但我得到了一个字符串。
我用这个从 axios 发送一个对象数组:
const data = [{
clientName: 'A client',
columns: [{
name: 'Keywords',
options: [{
keyword: false,
include: true
}]
}]
}]
await axios.post('/config', { data })
但是当我尝试查看选项的类型时,我得到的是字符串而不是布尔值
在后端我有这个
server.js
import express from 'express'
import cors from 'cors'
import config from './routes/config.js'
const prod = process.env.NODE_ENV === 'production'
const app = express()
// Middleware
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static('uploads'))
app.use('/config', config)
// Start
const port = process.env.PORT || prod ? 5002 : 4003
app.listen(port, () => console.log(`Listening on port ${port}.`))
还有路线
config.js
import { Router } from 'express'
import { writeFile } from 'fs/promises'
router.post('/config', async (req, res) => {
const { data } = req.body.data
// I want to write the data array with all of its objects however many they are, to file
await writeFile(config.json, JSON.stringify(data))
console.log(data)
}
export default router
[{
clientName: 'A client',
columns: [{
name: 'Keywords',
options: [{
keyword: 'false', // <-- string
include: 'true' // <-- string
}]
}]
}]
############## 更新
我的错,我以为 react 前端是在发送布尔值,结果它们实际上是字符串
<option value={true}>Keyword</option>
<option value={false}>Domain</option>
【问题讨论】:
-
不是我已经在使用
app.use(express.json())和app.use(express.urlencoded({ extended: true })),但它们以字符串形式返回 -
请包含快递应用和中间件的相关部分。
-
@Boaz 我已经添加了主服务器文件及其路由
-
检查 axios 请求的标头。您可能发送了错误的
Content-Type标头,因此无法将结果作为 JSON 处理,而是作为 url 编码的数据处理。