简体   繁体   中英

ReactJS: Fetch request to localhost php page

I'm in the process of learning PHP and integrating it into reactJS. However I've run into an odd issue that I can't seem to find a solution for.

Simple form below:

    class App extends React.Component {
    state = {
        company:'',
        person:'',
    };

    handleChange = (event) => {
        const target = event.target;
        const fieldName = target.name;
        const value = target.value;

        this.setState({
            [fieldName]: value,
        });
    };


    handleSubmit = async () => {
        let date = new Date();

        const headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
        };

        let submission = {
            method: "POST",
            headers: headers,
            body: {
                created: date,
                employee: {
                    company: this.state.company,
                    person: this.state.person,
                },
            }
        }

        let submitRequest = await fetch ('/src/php/requests.php', submission)
        <I tried using localhost/src/php to src/php to php/ to no effect
        console.log("Submit response: ",submitRequest)

    };

    render() {
        return (
            <div ><form><div>
                        <span style={{width: '150px'}}>
                            Company
                                <input
                                    name="company"
                                    type="text"
                                    onChange={this.handleChange}
                                />
                        </span></div>
                    <div><span style={{width: '150px'}}>
                            Name
                                <input
                                    name="person"
                                    type="text"
                                    onChange={this.handleChange}
                                />
                        </span> </div>
                    <button onClick={this.handleSubmit}> Submit </button>
                </form>
            </div>
        );
    }

}

export default App;

The app is meant to reference and send data to a locally hosted requests.php (below)

try {
$db = pg_connect("$host $port $dbname $login");
} catch(Exception $e) {
    print "Exception: " . $e->getMessage();
}
if(!$db){
    exit(pg_last_error() . "\n");
}
print "DB successful login \n";

$company = $person = $date = '';
$companyErr = $personErr = $dateErr = '';
$finalSubmission = '';

if ($_POST){
    appendLog($_POST); <simple logger to write post to file when received>
    return($_POST);
}

I know everything PHP side is working, but something is stuck between React and PHP, as I get the error

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

What am I doing wrong? All that changes is that the address bar refreshes with ?company=<name>&person=<name>

So the problem was multi-fold. Issue 1) has wonky behavior, causing all the initial issues. Removing Form fixed the webpage inserting stuff into the address bar, and also now allowed for CORS requests to go through. This was the main issue holding me up the last 2 days and threw me in for a loop. Just having a with that saved to state worked wonders.

Issue 2) There were some thing missing on my initial submission, which was added and reformatted. You can compare it to previous version above if need be.

    const headers = {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
    };

    let requestBody = {
        created: date,
        employee: {
            company: this.state.company,
            person: this.state.person
        }
    };

    let submission = {
        method: "POST",
        headers: headers,
        mode: 'cors',
        body:  JSON.stringify(requestBody),
        cache: 'no-cache',
        referrerPolicy: 'no-referrer',
    }

Issue 3) CORS needed proper parameters in headers, on PHP side. This was fixed by adding the code below. The key to it as well, is that it has to be the first thing at the top of the php file (as detailed below)

<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: *');
    http_response_code(200);
    return;
}

header('Access-Control-Allow-Origin: *');
header('COntent-Type: application/json');

...rest of PHP, include, and functions.

This solved my issue getting to the php file on my system. I ended up using "http://localhost:80/<website>/src/php/requests.php" to get to it.

Hope this helps anyone coming across a similar issue in the future. It was definitely a confusing one, since i had no idea interacted in that way with react.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM