You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含多词参数的HTTP请求无响应问题排查求助

多词参数传递API请求无返回结果排查

问题描述

开发软件工程课程的Leaflet Web应用时,遇到以下问题:向API传递空格分隔的多词参数(已尝试直接用空格或encodeURI编码),请求无任何返回结果;但用Postman调用相同端点能正常获取JSON数据。

请求流程

前端JS发起请求 → PHP后端 → 通过cURL调用目标API

示例场景

通过国家名称获取坐标以定位地图:

  • 单词国家名称请求正常,多词国家名称请求失效
  • 天气API接收多词城市名时存在同样问题,但Postman传递相同多词参数可正常返回

已尝试方案

  • 前端:使用axios、ajax、fetch三种请求方式
  • 后端:尝试cURL和file_get_contents()方法
  • 参数处理:直接用空格、encodeURI编码传递多词参数

关键代码片段

前端JS代码

//get list of countries
$(document).ready(function () {
    $('#loading-overlay').fadeOut('slow');

    axios.get('../assets/php/countriesRequest.php')
        .then(function (response) {
            countries = response.data.data;

            var selectElement = $('#countriesList select');

            // Make the first option selected as "select a country"
            var option = $('<option>').attr('value', '').text('Countries list');
            selectElement.append(option);

            // Renders the <select><option> elements with all countries
            countries.forEach(function (country) {
                var option = $('<option>').attr('value', country.countryName).text(country.countryName);
                selectElement.append(option);
            });

            // Get the country coordinates and set map view when the user selects a country
            selectElement.change(function () {
                var selectedCountry = $(this).val();
                axios.get('../assets/php/getCountryByName.php?countryName=' + selectedCountry)
                    .then(function (response) {
                        console.log(response.data.results[0]);
                        console.log(response.data.message);
                        var country = response.data.results[0].geometry;
                        coordinatesToTravel = [country.lat, country.lng];

                        console.log('Coordinates got from response: ', coordinatesToTravel);

                        // Set the map view to the selected country
                        map.setView(coordinatesToTravel, 5);
                        getCountryByLocation(coordinatesToTravel[0], coordinatesToTravel[1])

                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            });
        })
        .catch(function (error) {
            console.log(error);
        });
});

PHP:countriesRequest.php

<?php

require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../../');
$dotenv->load();

$geonamesUser = $_ENV['GEONAMES_API_USER'];

function getAllCountries($geonamesUser) {
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    if(isset($_REQUEST['countryCode'])) {
        $url = 'http://api.geonames.org/countryInfoJSON?username=' . $geonamesUser . '&country=' . $_REQUEST['countryCode'];
    } else {
        $url='http://api.geonames.org/countryInfoJSON?username=' . $geonamesUser;
    }


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];
    
    usort($output['data'], function ($a, $b) {
        return strcmp($a['countryName'], $b['countryName']);
    });
    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 
}

getAllCountries($geonamesUser);
?>

PHP:getCountryByName.php

<?php

require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../../');
$dotenv->load();

$opencage = $_ENV['OPENCAGE_API_KEY'];


    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    $url='https://api.opencagedata.com/geocode/v1/json?q=' . $_REQUEST['countryName'] . '&key=' . $opencage;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);

    $output = $decode;
    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['message'] = '$_REQUEST["countryName"] value got on php module: ' . $_REQUEST['countryName'];
    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 
?>

期望结果

传递多词参数时,请求能像传递单词参数一样正常返回JSON数据。


内容的提问来源于stack exchange,提问作者Victor Romero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:14:59