Я пытаюсь отправить этот json в конечную точку node express
{
"data": [
[
"Audit Territory",
"LA Antelope Valley",
"LA Central",
"LA East San Gabriel",
"LA San Fernando Valley",
"LA West",
"LA West San Gabriel",
"OR Inland, Coastal South",
"OR West",
"RV Central",
"RV Coachella Valley",
"RV South, Central",
"SB High Desert",
"Unassigned"
],
[
"Auditor Name",
"Jeanna Bonds",
"Dawn Wiley",
"Janet Cortez",
"Benjamin Sally",
"Margie Watkins",
"Jennifer Perich",
"Tami Anderson",
"Christy Brant",
"Brian Lopiccolo",
"Kristina Clark",
"Tina Chester",
"Ira Brown",
" Unassigned"
],
[
"Not Started",
20,
13,
24,
25,
24,
52,
117,
33,
48,
54,
44,
69,
2
],
[
"In Progress",
1,
2,
0,
1,
1,
1,
1,
0,
0,
0,
18,
0,
0
],
[
"Could Not Complete",
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
"Ready for Review",
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
0,
0
],
[
"Needs More Research",
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
"Approved",
1,
0,
0,
1,
1,
0,
2,
0,
1,
1,
3,
3,
0
]
],
"colWidths": [
25,
25,
25,
25,
30,
30,
30,
25
],
"colStyles": [
{},
{},
{
"horizontalAlignment": "center"
},
{
"horizontalAlignment": "center"
},
{
"horizontalAlignment": "center"
},
{
"horizontalAlignment": "center"
},
{
"horizontalAlignment": "center"
},
{
"horizontalAlignment": "center"
}
]
}
Он неправильно разбирается в экспрессе, и я пытаюсь понять, что нужно. Я пробовал несколько разных вещей.
Я установил body-parser и применил его глобально
app.use (bodyParser.urlencoded ({extended: true}))
это ничего не изменило.
* POST от клиента
const _fetch = model => {
return fetch(`http://0.0.0.0:9000/create-excels`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(model)
}).then(statusHelper).then(response => response.json())
}
Я попытался настроить модель, созданную автоматически для этого API.
const createExcelSchema = new Schema({
data: {
type: [[]] // Array
},
colWidths: {
type: Array
},
colStyles: {
type: [{}] // Array
}
}, {
timestamps: true,
toJSON: {
virtuals: true,
transform: (obj, ret) => { delete ret._id }
}
})
Это повлияло на результат, но не решило проблему. Вот результат, который я получаю
{
"data": [
[
"Audit Territory",
"LA Antelope Valley",
"LA Central",
"LA East San Gabriel",
"LA San Fernando Valley",
"LA West",
"LA West San Gabriel",
[
"OR Inland",
"Coastal South"
],
"OR West",
"RV Central",
"RV Coachella Valley",
[
"RV South",
"Central"
],
"SB High Desert",
"Unassigned"
],
[
"Auditor Name",
"Jeanna Bonds",
"Dawn Wiley",
"Janet Cortez",
"Benjamin Sally",
"Margie Watkins",
"Jennifer Perich",
"Tami Anderson",
"Christy Brant",
"Brian Lopiccolo",
"Kristina Clark",
"Tina Chester",
"Ira Brown",
"Unassigned"
],
[
"Not Started",
"20",
"13",
"24",
"25",
"24",
"52",
"117",
"33",
"48",
"54",
"44",
"69",
"2"
],
[
"In Progress",
"1",
"2",
"0",
"1",
"1",
"1",
"1",
"0",
"0",
"0",
"18",
"0",
"0"
],
[
"Could Not Complete",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
],
[
"Ready for Review",
"2",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"4",
"0",
"0"
],
[
"Needs More Research",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
],
[
"Approved",
"1",
"0",
"0",
"1",
"1",
"0",
"2",
"0",
"1",
"1",
"3",
"3",
"0"
]
],
"colWidths": "25,25,25,25,30,30,30,25",
"colStyles": [
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]"
]
}
контролер
export const create = ({ bodymen: { body } }, res, next) => {
_createExcel(body.data, body.colWidths, body.colStyles).then(result => success(res.status(201).json(result)))
.catch(next)
}
маршрут
import { Router } from 'express'
import { middleware as body } from 'bodymen'
import { create } from './controller'
import { schema } from './model'
export CreateExcel, { schema } from './model'
const router = new Router()
const { data, colWidths, colStyles } = schema.tree
router.post('/',
body({ data, colWidths, colStyles }),
create)
модель
import mongoose, { Schema } from 'mongoose'
const createExcelSchema = new Schema({
data: {
type: [[]]
},
colWidths: {
type: Array
},
colStyles: {
type: [{}]
}
}, {
timestamps: true,
toJSON: {
virtuals: true,
transform: (obj, ret) => { delete ret._id }
}
})
createExcelSchema.methods = {
view (full) {
const view = {
// simple view
id: this.id,
data: this.data,
colWidths: this.colWidths,
colStyles: this.colStyles,
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
return full ? {
...view
// add properties for a full view
} : view
}
}
const model = mongoose.model('CreateExcel', createExcelSchema)
export const schema = model.schema
export default model
Я только что добавил больше информации.
не могли бы вы показать мне, как вы публикуете эти данные для выражения api? вы устанавливаете заголовок типа содержимого на application/x-www-form-urlencoded?
только что выложил. Я пытался изменить это app.use (bodyParser.urlencoded ({extended: true})) (bodyParser.urlencoded) на (bodyParser.json)
Я просто пробую как можно больше разных вещей, прежде чем обратиться за помощью
@ texas697 В исходном JSON отсутствует закрывающая фигурная скобка в конце данных. Добавьте это и посмотрите, допустим ли ваш JSON формат.
Это здесь. просто нужно исправить форматирование здесь



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Что ж, я собираюсь предположить, что вы не публикуете JSON в URL-адресе, что означает применение
app.use(bodyParser.urlencoded({ ... }))
На самом деле тебе не поможет. Скорее всего, вам понадобится промежуточное ПО json, которое будет анализировать тело в формате JSON.
app.use(bodyParser.json())
вот результат
[«ИЛИ Внутренний», «Прибрежный юг»]
последнее .. Фактическое значение - "OR Inland, Costal South", оно рассматривается как отдельный массив.
Я могу решить проблему, заменив "," на что-то другое, прежде чем отправлять
Покажи свой маршрут. Как вы получаете доступ к переменным объекта
request?