Публикация данных json в моей базе данных с помощью axios (используя мой бэкэнд API)

У меня очень странная проблема. У меня есть бэкэнд API для импорта данных JSON в мой mongodb.

На экране у меня есть кнопка загрузки, чтобы загрузить файл, и я использовал для этого реактив-dropzone. Например, подумайте, что у меня есть файл, например, "db.json", и в этом файле есть json, как показано ниже

{
"datapointtypes":[
    {"id":"Wall plug","features":[{"providesRequires":"provides","id":"Binary switch"},{"providesRequires":"requires","id":"Binary sensor","min":"1","max":"2"}],"parameters":[{"id":"Communication type","type":"Communication type"}],"functions":[{"id":"Electricity"},{"id":"Switch"}]},
    {"id":"Door sensor","features":[{"providesRequires":"provides","id":"Binary sensor"}],"parameters":[{"id":"Communication type","type":"Communication type"}],"functions":[{"id":"Door"},{"id":"Sensor"}]}
],
"datatypes":[
    {"id":"Communication type","type":"enum","values":[{"id":"Zwave"},{"id":"Zigbee"}]},
    {"id":"Zigbee network address","type":"decimal","min":1,"max":65336,"res":1},
    {"id":"Serial port","type":"string"}
],
"features":[
    {"id":"Zwave receiver","exposedtype":"Zwave command","functions":[{"id":"Communication"}]},
    {"id":"Zigbee receiver","exposedtype":"Zigbee command","functions":[{"id":"Communication"}]},
    {"id":"Binary switch","exposedtype":"On off state","functions":[{"id":"Actuator"}]},
    {"id":"Binary sensor","exposedtype":"On off state","functions":[{"id":"Sensor"}]}
],
"servicetypes":[
    {"id":"Room controller","datapointtype":"Room controller","DelayActive":false,"DelayValue":""},
    {"id":"Xiaomi door sensor","datapointtype":"Door sensor","parameters":[{"id":"Zigbee network address","type":"Zigbee network address"},{"id":"Zigbee node id","type":"Zigbee node id"}],"parametervalues":[{"id":"Communication type","value":"Zigbee"}]}
],
"systems":[
    {"id":"system 2","services":[{"serviceType":"Room controller","id":"servis 1"}],"serviceRelations":[{"serviceName":"servis 1","featureName":"Binary sensor"}],"parametervalues":[{"id":"Delay","paramName":"Delay","serviceType":"Room controller","value":"binary"}]},
    {"id":"system 3","services":[{"serviceType":"Room controller","id":"servis 1"}],"serviceRelations":[{"serviceName":"servis 1","featureName":"Binary sensor"}],"katid":"7"}
]
}

Проблема в этом. Если консоль браузера открыта, мой код успешно работает, и я могу импортировать данные json в мой mongodb. Но если консоль браузера закрыта, я получаю ошибку "SyntaxError: Неожиданный конец ввода JSON".

Это функция, которую я использую на кнопку импорта

class FileUpload extends Component {
state = {
    warning: ""
}

uploadFile = (files, rejectedFiles) => {
    files.forEach(file => {
        const reader = new FileReader();

        reader.readAsBinaryString(file);
        let fileContent = reader.result;

        axios.post('http://localhost:3001/backendUrl', JSON.parse(fileContent),
            {
                headers: { 
                    "Content-Type": "application/json" 
                }
            })
            .then(response => {
                this.setState({warning: "Succeed"})
            })
            .catch(err => {
                console.log(err)
            });
    });
}

render() {
    return (
        <div>
            <Dropzone className="ignore" onDrop={this.uploadFile}>{this.props.children}
            </Dropzone>
            {this.state.warning ? <label style={{color: 'red'}}>{this.state.warning}</label> : null}
        </div>
    )
}

}

Что это я делаю что-то не так или чем это вызвано? Вы можете мне помочь?

Спасибо

1 ответ

FileReader читает файлы асинхронно, поэтому вы должны использовать обратный вызов для доступа к результатам
я хотел бы использовать readAsText вместо readAsBinaryString в случае, если в JSON нет символов ascii
В заключение, JSON.parse преобразует строку JSON в объект (или любой другой тип). fileContent это уже JSON, так что оставьте все как есть.

    const reader = new FileReader();
    reader.onlooad = (e) => {
        let fileContent = this.result;

        axios.post('http://localhost:3001/backendUrl', fileContent,
        {
            headers: { 
                "Content-Type": "application/json" 
            }
        })
        .then(response => {
            this.setState({warning: "Succeed"})
        })
        .catch(err => {
            console.log(err)
        });
    }
    reader.readAsText(file);
Другие вопросы по тегам