【问题标题】:Malformed JSON object格式错误的 JSON 对象
【发布时间】:2022-06-10 21:20:11
【问题描述】:

我知道有很多类似的问题,但没有一个能满足我的需求。我正在尝试在我的 PHP 后端从反应前端接收 JSON 对象。

BackendHelper.tsx

const BACKEND_API = 'https://URL_TO_BACKEND/?action=';

export async function post(endpoint: string, data: unknown) {
let response = await fetch(BACKEND_API + endpoint);
await fetch(BACKEND_API + endpoint, {
    method:  'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    redirect: 'follow',
    body:JSON.stringify(data),
});
return await response.json();
}

我有另一个类来插入我需要的参数

LogLogin.tsx

import {post} from './BackendHelper';

export class LogLogin {
public static log(username: FormDataEntryValue, password: FormDataEntryValue): Promise<unknown> {
    return post('logLogin', {username: username, password: password});
}

loginForm.tsx我有这行代码await LogLogin.log(data.get('email'), data.get('password'));来执行这个功能。

在后端,我尝试这样做: $data = json_decode(file_get_contents('php://input'), true); 由于它总是只返回一个 int 1 我发现使用 json_last_error 它返回一个 Syntax error, malformed JSON React

我真的不明白如何使用我当前的代码创建格式错误的 JSON 对象 :)

【问题讨论】:

  • 首先检查 file_get_contents('php://input') 实际包含的内容。
  • 如前所述,它只包含1
  • 你的内容应该自动解析成$_POST,不需要php://input
  • @Justinas,不,不是当请求以Content-Type: application/json 发送时

标签: php reactjs json


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
相关资源
最近更新 更多