之前已經問過這個問題,但問題沒有解決發送方法,并且標記的解決方案對我不起作用。
我試圖在后端的 JSON 物件中獲取布林值,但我得到了一個字串。
我用這個從 axios 發送一個物件陣列:
const data = [{
clientName: 'A client',
columns: [{
name: 'Keywords',
options: [{
keyword: false,
include: true
}]
}]
}]
await axios.post('/config', { data })
但是當我嘗試查看選項的型別時,我得到的是字串而不是布林值
在后端我有這個
服務器.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}.`))
還有路線
配置.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
}]
}]
}]
############## 更新
我的錯,我以為反應前端正在發送布林值,結果它們實際上是字串
<option value={true}>Keyword</option>
<option value={false}>Domain</option>
uj5u.com熱心網友回復:
假設整個物件不是字串,只有值是字串,您可以決議它們。
JSON.parse(data[0].columns[0].options[0].keyword);
uj5u.com熱心網友回復:
我認為這是錯誤的
app.use(express.urlencoded({extended: true }))
您正在使用 urlencoded
你需要使用bodyParser,這樣做是為了匯入body-parser
var bodyParser = require('body-parser');
并使用它
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409211.html
標籤:
