面试题答案
一键面试用户未授权访问
- HTTP状态码:401 Unauthorized。该状态码表示请求要求身份验证,当用户尝试访问需要认证但未提供有效凭证时使用。
- 后端设置:在后端代码中,以Python的Flask框架为例,如果检测到用户未提供认证信息或认证失败,可以这样设置状态码:
from flask import Flask, jsonify, make_response
app = Flask(__name__)
@app.route('/protected')
def protected():
# 假设这里检测到用户未授权
response = jsonify({'error': 'Unauthorized access'})
return make_response(response, 401)
if __name__ == '__main__':
app.run(debug=True)
在Java的Spring Boot框架中,可如下设置:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@GetMapping("/protected")
public ResponseEntity<String> protectedResource() {
// 假设这里检测到用户未授权
return new ResponseEntity<>("Unauthorized access", HttpStatus.UNAUTHORIZED);
}
}
资源不存在
- HTTP状态码:404 Not Found。此状态码表明服务器无法找到请求的资源,当用户请求一个不存在的资源路径或资源本身已被删除等情况适用。
- 后端设置:以Python的Django框架为例,若查找资源未找到,可以这样设置状态码:
from django.http import Http404, JsonResponse
def my_view(request):
try:
# 尝试获取资源
resource = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404('Resource not found')
return JsonResponse({'data': resource.data})
在Node.js的Express框架中,示例如下:
const express = require('express');
const app = express();
app.get('/resource/:id', (req, res) => {
const resourceId = req.params.id;
// 假设这里查找资源未找到
if (!resourceExists(resourceId)) {
return res.status(404).json({ error: 'Resource not found' });
}
// 返回资源
return res.json({ data: getResource(resourceId) });
});
function resourceExists(id) {
// 实际资源存在判断逻辑
return false;
}
function getResource(id) {
// 实际获取资源逻辑
return {};
}
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});