如何使用本地PHP文件实现fetch函数?调用失败问题求助
Hey there, let's work through your fetch issues step by step—since your online calls work, the problem is definitely tied to your local setup. Let's break down each error and fix them:
First Error: Attempt to invoke virtual method 'boolean java.lang.string(java.lang.Object' on a null object reference
This error is almost certainly caused by a syntax mistake in your fetch call. You wrote:
fetch(./submitData.php, { method: 'POST', headers: { ... } })
The issue here is that ./submitData.php isn't wrapped in quotes—JavaScript treats it as an undefined variable (which is null), hence the null reference error. Correct the path to be a string:
fetch('./submitData.php', { method: 'POST', headers: { ... } })
Second Error: network request failed (after switching to https://localhost/submitData.php)
When you switched to the full URL, the network failure can stem from a few common local server issues. Let's check each one:
- Check if your local server is running: Make sure Apache/Nginx (or whatever server you're using for PHP) is up and running. Try accessing
http://localhost/submitData.phpdirectly in your browser—if it loads, the server is working; if not, start your server first. - Drop the HTTPS (unless you have a valid local SSL cert): Most local dev servers don't come with a valid SSL certificate by default. Using
https://will trigger security errors. Switch tohttp://localhost/submitData.phpinstead. - Fix CORS issues: If your frontend is running on a different port (e.g., a React dev server on
localhost:3000) or loaded viafile://(directly opening the HTML file), your browser will block the request due to CORS. Add these headers at the top of yoursubmitData.phpfile to allow local requests (only use this in development):header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Content-Type"); - Verify the file path: Double-check that
submitData.phpis actually in the root directory of your local server. If it's in a subfolder (e.g.,http://localhost/my-project/submitData.php), update the URL in your fetch call to match. - Check request header compatibility: If you're sending JSON data in your fetch body, ensure your headers include
Content-Type: application/json, and in PHP, usefile_get_contents('php://input')to read the data (since$_POSTonly handles form-encoded data). Example:
And in PHP:fetch('http://localhost/submitData.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ yourData: 'value' }) })$data = json_decode(file_get_contents('php://input'), true);
Start with the simplest fixes first (checking server status, fixing the URL syntax, switching to HTTP) and work your way through—you should have this sorted in no time!
内容的提问来源于stack exchange,提问作者pjconcepcion

