ExpressJS与AJAX请求调用失败求助:无法完成简单AJAX调用
Hey there! Let’s work through why your AJAX call might be failing and get it up and running. First, let’s fill in that missing HTML/JavaScript code for your button, then go through the most common pitfalls to check.
第一步:补全前端代码示例
Create an index.html file inside your public folder (since your server uses express.static("public")), with this code:
<!DOCTYPE html> <html> <head> <title>AJAX Test</title> </head> <body> <button id="testBtn">Send AJAX Request</button> <div id="responseArea"></div> <script> const testButton = document.getElementById('testBtn'); const responseArea = document.getElementById('responseArea'); testButton.addEventListener('click', () => { // Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Configure the request: GET method, target URL, async = true xhr.open('GET', '/test1', true); // Handle successful response xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { responseArea.textContent = `Success! Server said: ${xhr.responseText}`; } else { responseArea.textContent = `Server error! Status code: ${xhr.status}`; } }; // Handle network-level errors xhr.onerror = function() { responseArea.textContent = "Network error! Couldn't reach the server."; }; // Send the request xhr.send(); }); </script> </body> </html>
If you prefer using jQuery, here’s an alternative snippet (just add the jQuery CDN first):
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $('#testBtn').click(function() { $.get('/test1') .done(function(data) { $('#responseArea').text(`Success! Server said: ${data}`); }) .fail(function(jqXHR, textStatus) { $('#responseArea').text(`Request failed: ${textStatus}`); }); }); </script>
第二步:逐一排查常见问题
1. 验证服务器是否正常运行
First, make sure your Express server is up:
- Run
npm install expressif you haven’t already installed the dependency. - Start your server with
node your-server-file.js(replace with your actual filename). - Open your browser and go directly to
http://localhost:8888/test1. If you seeGET request to the homepage, your server is working. If not, check for typos in your server code or port number.
2. 通过服务器访问前端(不要直接打开文件!)
Don’t double-click the index.html file to open it (this uses the file:// protocol, which triggers CORS errors). Instead, go to http://localhost:8888/index.html in your browser—this keeps your front-end and server on the same origin, avoiding cross-domain issues.
3. 用开发者工具检查请求细节
Open your browser’s DevTools (F12), go to the Network tab, then click your button. Look at the request for /test1:
- If status is
404: You have a typo in your AJAX URL (make sure it’s exactly/test1). - If status is
CORS Error: You’re accessing the front-end viafile://or a different port—fix this by usinghttp://localhost:8888. - If status is
200but no response shows up: Check your JavaScript for typos (e.g., misspelled element IDs, broken event listeners).
4. 在服务器添加日志确认请求到达
Modify your server’s /test1 route to log incoming requests—this tells you if the request is even reaching the server:
app.get('/test1', function (req, res) { console.log('Got a GET request to /test1!'); // 新增日志行 res.send('GET request to the homepage'); });
If you see this log in your server console when you click the button, the problem is in your front-end’s response handling. If not, the request isn’t being sent correctly.
内容的提问来源于stack exchange,提问作者Kageyasha

