使用XMLHttpRequest发POST请求遇403及JSON格式错误求助
Hey there, let's work through your issues one by one to get your POST requests working correctly:
1. Fixing the 403 Authentication Error
That 403 status code tells me the server isn't accepting your authentication attempt. Here are a few likely issues and fixes to try:
- Synchronous request limitations: You’re using a synchronous XMLHttpRequest (the third parameter in
open()isfalse). This approach is generally discouraged, and some servers/environments restrict how auth credentials are passed in sync requests. Switching to an asynchronous request (set that parameter totrue) is a solid first step. - Incorrect auth method: The
loginandpasswordparameters inopen()are for HTTP Basic Auth, but your server might expect a different method—like a Bearer Token from a login session, or an API key in a custom header. If it does use Basic Auth, manually constructing theAuthorizationheader is more reliable than relying on theopen()parameters:const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; const http = new XMLHttpRequest(); const url = "https://mywebsite.com/api/comment"; const params = 'comment=test'; const login = "your-actual-username"; const password = "your-actual-password"; // Encode credentials for Basic Auth const authHeader = `Basic ${btoa(`${login}:${password}`)}`; http.open("POST", url, true); // Use async request instead of sync http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Authorization", authHeader); // Handle the response properly with async logic http.onload = function() { if (this.status >= 200 && this.status < 400) { console.log("Request succeeded:", this.responseText); } else { console.error(`Error ${this.status}:`, this.responseText); } }; http.onerror = function() { console.error("Request failed to connect to the server"); }; http.send(params); - Credential typos: Double-check that your
loginandpasswordvariables are correctly assigned—small typos here are an easy mistake to make!
2. Resolving the "Not JSON" Login Error
The {"status":"nok","message":"Not JSON"} response means the server expects a JSON-formatted request body, but you’re probably sending form-encoded data instead. Here’s how to adjust your login request:
- Send JSON payload instead of form data, and set the correct
Content-Typeheader:const loginUrl = "https://mywebsite.com/api/login"; const loginPayload = JSON.stringify({ username: login, password: password }); const loginHttp = new XMLHttpRequest(); loginHttp.open("POST", loginUrl, true); loginHttp.setRequestHeader("Content-Type", "application/json"); loginHttp.onload = function() { try { const response = JSON.parse(this.responseText); if (response.status === "ok") { // If login returns an auth token, use it for your comment request const authToken = response.token; const commentHttp = new XMLHttpRequest(); commentHttp.open("POST", url, true); commentHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); commentHttp.setRequestHeader("Authorization", `Bearer ${authToken}`); commentHttp.send(params); } else { console.error("Login failed:", response.message); } } catch (err) { console.error("Failed to parse login response:", err); } }; loginHttp.send(loginPayload);
3. Quick Troubleshooting Checks
- Test with curl/Postman: Before debugging code, test your login and comment endpoints with a tool like curl or Postman. This will confirm if the issue is with your code or the server setup. For example, a curl login request might look like:
curl -X POST https://mywebsite.com/api/login \ -H "Content-Type: application/json" \ -d '{"username":"your-login","password":"your-password"}' - Check server logs: If you have access to the server’s logs, they’ll give you detailed info about why authentication is failing or why the request format is rejected.
- Verify API docs: Make sure you’re following the server’s official API documentation—endpoints often specify exact auth methods, request formats, and required headers.
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

