Restful Api Debug
## Testing APIs Using Tools
### 1. Testing with Postman
Postman is the most popular API testing tool, acting as an "experimental field" for APIs.
Postman official website: [https://www.postman.com/](https://www.postman.com/).
!(#)
**Basic Testing Steps**:
1. Create a new request
2. Set the HTTP method (GET, POST, etc.)
3. Enter the API URL
4. Add request headers and body
5. Send the request and view the response
**Postman Collection Example**:
```json
{
"info": {
"name": "User Management API Test",
"description": "Testing all API endpoints related to users"
},
"item": [
{
"name": "Get User List",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/api/users?page=1&limit=10",
"host": ["{{baseUrl}}"],
"path": ["api", "users"],
"query": [
{"key": "page", "value": "1"},
{"key": "limit", "value": "10"}
]
}
}
}
]
}
### 2. Testing with curl Command Line
# Get user list
```bash
curl -X GET "https://api.example.com/users"
-H "Content-Type: application/json"
# Create a new user
```bash
curl -X POST "https://api.example.com/users"
-H "Content-Type: application/json"
-d '{ "name": "Zhang San", "email": "zhangsan@example.com" }'
# Update user information
```bash
curl -X PUT "https://api.example.com/users/123"
-H "Content-Type: application/json"
-d '{ "name": "Li Si", "email": "lisi@example.com" }'
# Delete a user
```bash
curl -X DELETE "https://api.example.com/users/123"
-H "Content-Type: application/json"
### 3. Browser Developer Tools
```javascript
// Test fetch in browser console
fetch('/api/users', { method: 'GET', headers: { 'Content-Type': 'application/json' } })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
* * *
## Common Issues and Debugging
### 1. CORS Cross-Origin Issues
Error message:
Access to fetch at 'https://api.example.com/users' from origin 'http://localhost:3000' has been blocked by CORS policy
Solution:
```javascript
// Server-side needs to set CORS headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
### 2. Status Code Errors
Common errors and their causes:
| Status Code | Possible Causes | Solutions |
| --- | --- | --- |
| 400 | Incorrect request data format | Check JSON format and required fields |
| 401 | Authentication failed | Verify that the Token is correct |
| 404 | Incorrect API path | Confirm the URL spelling is correct |
| 500 | Internal server error | Review server logs |
### 3. Data Format Issues
```json
// Incorrect request format
{
name: "Zhang San", // ❌ missing quotes
email: "test@example.com", // ❌ single quotes
age: "25" // ❌ using string for number
}
// Correct request format
{
"name": "Zhang San", // ✅ double quotes
"email": "test@example.com", // ✅ double quotes
"age": 25 // ✅ numeric type
}
* * *
## Automated Testing
### Unit Test Example
## Example
```javascript
describe('User API Tests', () => {
test('Should be able to get user list', async () => {
const response = await fetch('/api/users');
const data = await response.json();
expect(response.status).toBe(200);
expect(data.success).toBe(true);
expect(Array.isArray(data.data)).toBe(true);
});
test('Should be able to create a new user', async () => {
const newUser = {
name: "Test User",
email: "test@example.com"
};
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
});
const data = await response.json();
expect(response.status).toBe(201);
expect(data.success).toBe(true);
expect(data.data.name).toBe(newUser.name);
});
});
YouTip