Запрос POST не работает в React Native Expo, но запрос GET работаетPhp

Кемеровские программисты php общаются здесь
Anonymous
Запрос POST не работает в React Native Expo, но запрос GET работает

Сообщение Anonymous »

Я пытаюсь войти в систему методом POST, но данные в запросе не принимаются сервером. Я попробовал это в Postman, и данные были успешно отправлены. Сначала я попробовал использовать Axios, затем Fetch API, но ни один из них не помог. Однако когда я попробовал это с помощью запроса GET, все сработало отлично.
import axios from 'axios';
import React from 'react';
import { appPackageName, ApiKey, ApiServer } from '@/constants';
import { MyObject } from '@/interface';
import { Platform } from 'react-native';

const headers: MyObject = {
'Content-Type': 'application/json',
};

if (Platform.OS !== 'web') {
headers['APP_PACKAGE_NAME'] = appPackageName;
}

Это запрос Axios:
export async function postData(relativeUrl: string, requestData: MyObject): Promise {
try {
headers['Authorization'] = `Bearer ${ApiKey}`;

console.log({ ...requestData });

const response = await axios.post(
`${ApiServer}/${relativeUrl}`,
{ ...requestData }, // I tried with JSON.stringify(requestData) and without the spread or stringify as well
{
headers: headers,
withCredentials: true,
}
);

return response.data;
} catch (error) {
// Handle the error
console.error('Error fetching data:', error);
throw new Error('Failed to fetch data');
}
}

Это запрос на выборку:
export async function postData(relativeUrl: string, requestData: MyObject): Promise {
try {
headers['Authorization'] = `Bearer ${ApiKey}`;

console.log({ ...requestData });

const response = await fetch(`${ApiServer}/${relativeUrl}`, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestData),
});

console.log(response);

const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw new Error('Failed to fetch data');
}
}

Это метод запроса GET:
export async function getData(relativeUrl: string, requestData: MyObject): Promise {
try {
const response = await axios.get(
`${ApiServer}/${relativeUrl}`,
{
headers: headers,
params: requestData,
}
);
console.log(response.data);

return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw new Error('Failed to fetch data');
}
}

Это заголовок запроса браузера:
POST /public/auth/login HTTP/1.1
Host: localhost:9016
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Content-Type: application/json
Authorization: Bearer TOKEN_CODE
Content-Length: 97
Origin: http://localhost:8081
Connection: keep-alive
Referer: http://localhost:8081/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Priority: u=0

Это заголовок запроса Postman:
Cookie: PHPSESSID=vcug376r85rus7fj3aep0pivmm
Cache-Control: no-cache
Postman-Token:
Content-Type: multipart/form-data; boundary=
Content-Length:
Host:
User-Agent: PostmanRuntime/7.39.1
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Authorization: Bearer TOKEN_CODE
Content-Type: application/json

Это проверка php CORS
/**
* Set up headers that handle API requests
*/
require_once $_SERVER['DOCUMENT_ROOT'].'/src/env-var.php';

$headers = getallheaders();

// Get the request's Origin header
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type, HTTP_X_APP_PACKAGE_NAME");

if (isset($headers['Authorization']) || isset($headers['Credentials'])) {
header('Access-Control-Allow-Credentials: true');
}

header('Access-Control-Max-Age: 86400'); // Cache for 1 day
header('Content-Type: application/json');
exit(0);
}

// Set general CORS headers
header('Content-Type: application/json');

if(preg_match('/development/',ENV)){
header("Access-Control-Allow-Origin: *");
}
else if (isset($_SERVER['HTTP_X_APP_PACKAGE_NAME']) && in_array($_SERVER['APP_PACKAGE_NAME'], $allowedApps))
header("Access-Control-Allow-Origin: *");
elseif (isset($_SERVER['HTTP_ORIGIN']) && in_array($origin, $allowedOrigins))
header("Access-Control-Allow-Origin: $origin");
else {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized Access']);
exit;
}

// Allow credentials if the request includes Authorization or Credentials header
if (isset($headers['Authorization']) || isset($headers['Credentials'])) {
header('Access-Control-Allow-Credentials: true');
}

// Allow specified methods
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

// Allow specific headers
header("Access-Control-Allow-Headers: Authorization, Content-Type, X-Custom-Header");

// Cache for 1 day
header('Access-Control-Max-Age: 86400');


Подробнее здесь: https://stackoverflow.com/questions/787 ... is-working

Вернуться в «Php»