使用request包持续返回401错误,请求代码问题排查
Hey, let's work through that 401 error you're seeing—this is almost always an authentication or configuration issue with your Mailchimp setup. Here are the key fixes you need to make:
1. Fix the Authorization Header Format
Mailchimp's API expects a specific format for the authorization header: Authorization: [AnyRandomString] YourActualApiKey. The first part can be any text (many people use their username, but it doesn't matter) followed by a space and your real API key.
Right now, you're using placeholder text ("mkouk24 Api Key") instead of your actual key. Update it like this:
headers: { "Authorization": "myUsername 123abcxyz-us20" // Replace 123abcxyz-us20 with your real API key }
2. Replace the List ID Placeholder
Your API URL has listId as a placeholder—you need to swap this with your actual Mailchimp list ID (you can find this in your list's settings page in Mailchimp). The corrected URL should look like:
url: "https://us20.api.mailchimp.com/3.0/lists/abc123def456" // Replace abc123def456 with your list ID
While this won't cause a 401 (it'll throw a 404 if wrong), it's critical to fix once authentication is sorted.
3. Match API Key Region to URL
Double-check that the region in your URL (us20) matches the suffix of your API key. Mailchimp keys end with a region code like -us20—if your key ends with -us19, for example, you need to update the URL to https://us19.api.mailchimp.com/3.0/....
Bonus: Hardcoded Key Best Practice
Avoid hardcoding your API key directly in your code (especially if you're pushing to version control). Use environment variables instead—you can use the dotenv package to manage this easily.
Corrected Code Example
Here's your code with all the fixes applied (fill in the placeholders with your actual values):
const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const app = express(); app.use(express.static("public")); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/signup.html"); }); app.post("/", function(req, res){ var firstName = req.body.firstName; var lastName = req.body.lastName; var email = req.body.email; var data = { members: [ { email_address: email, status: "subscribed", merge_fields: { // Optional: save first/last name to your Mailchimp list FNAME: firstName, LNAME: lastName } } ] }; var jsonData = JSON.stringify(data); // Replace these with your actual Mailchimp credentials const MAILCHIMP_API_KEY = "your-real-api-key-us20"; const MAILCHIMP_LIST_ID = "your-real-list-id"; var options = { url: `https://us20.api.mailchimp.com/3.0/lists/${MAILCHIMP_LIST_ID}`, method: "POST", headers: { "Authorization": "any-string-you-want " + MAILCHIMP_API_KEY }, body: jsonData }; request(options, function(error,response,body){ if (error) { console.log(error); res.send("Oops, something went wrong with your subscription!"); // Give user feedback } else { console.log(response.statusCode); if (response.statusCode === 200) { res.send("Successfully subscribed—thanks!"); } else { res.send("Sorry, we couldn't subscribe you right now."); } } }); }); app.listen(3000, function() { console.log("Server is running on port 3000!"); });
After making these changes, your request should authenticate properly and stop returning the 401 error.
内容的提问来源于stack exchange,提问作者Matthew Koukios

