JavaScript调用Wizzair API:POST传Payload遇404问题求解
Let's sort out why your request is returning a 404 and get it working correctly. Here are the key issues with your current code and how to fix them:
1. You're Passing Payload the Wrong Way
Your code appends the payload to the URL (url+payload), which is how you'd send data in a GET request. For POST requests, the payload needs to be sent in the request body—not tacked onto the end of the URL.
2. Incorrect type Parameter
In jQuery's $.ajax, the type parameter defines the request method (GET/POST). You set it to "json"—that's a mistake. Instead, use dataType: "json" to tell jQuery you expect a JSON response, and keep method: "POST" (or type: "POST" for older jQuery versions) for the request method itself.
3. Missing Required Content-Type Header
To send JSON data in a POST request, you need to set the Content-Type header to application/json. Without this, the server might not recognize the payload format, leading to a 404 or invalid request error.
4. (Optional) Add Browser-like Request Headers
Many APIs block requests that don't look like they're coming from a browser. Adding a User-Agent header matching a modern browser can help avoid being flagged as a non-browser request.
Corrected Code Example
const url = "https://be.wizzair.com/7.10.1/Api/search/search"; const payload = { // Replace with your actual payload structure from dev tools departureStation: "BUD", arrivalStation: "PMI", departureDate: "2024-06-01", // ... include all other required fields you saw in the browser's XHR payload }; $.ajax({ method: "POST", url: url, data: JSON.stringify(payload), // Convert payload object to JSON string contentType: "application/json", // Critical for telling server to parse JSON dataType: "json", // Expect a JSON response from the server headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" }, success: function (data) { console.log("Request succeeded!", data); }, error: function (xhr, ajaxOptions, thrownError) { console.error("Error status code:", xhr.status); console.error("Server response:", xhr.responseText); console.error("Error message:", thrownError); } });
Additional Tips
- Match the payload exactly: Double-check that your payload includes all fields and uses the same naming/casing as the request you saw in DevTools. Missing or misnamed fields can cause errors even if the request is formatted correctly.
- Copy headers from DevTools: Some APIs require additional headers like
AcceptorX-Requested-With. Copy these directly from the browser's request headers to replicate the exact request the browser sends. - Test with Postman first: Before writing code, replicate the request in Postman using the exact headers and payload from DevTools. This confirms the request works outside of jQuery, making it easier to debug code-specific issues.
内容的提问来源于stack exchange,提问作者J. Doe

