In projects separated by front-end, back-end, the front-end (usually a single-page application based on frameworks such as Vue, React, Angular) and the back-end (usually an API service based on PHP, Node.js, Python, etc.) interact through the HTTP interface. To ensure that API responses can be handled correctly by the front-end, avoid cross-domain issues, ensure security and standardization, we must set up the HTTP response header correctly.
In PHP, the most commonly used tool is the header() function. This article will use specific examples to explain how to use the header() function to set common API response headers in front-end separation projects.
The data returned by the API is generally in JSON format, so you need to tell the front-end and the client this point.
header('Content-Type: application/json; charset=utf-8');
This line of code indicates that the returned data type is JSON and the character set is UTF-8. The front-end can correctly parse the response based on this information.
When the current and backend are not in the same domain, the browser will intercept the request. We need to add cross-domain response headers to allow front-end access.
header('Access-Control-Allow-Origin: https://m66.net');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
These settings allow front-end access to the API from https://m66.net and allow specified request methods and custom request headers. Note: It is best not to use * in production environments, but to specify specific domain names to improve security.
To ensure that the front-end gets the latest data every time, caching can be disabled:
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
These response headers will notify the client and proxy server not to cache the returned content.
Sometimes you not only need to return data, but also set the corresponding HTTP status code.
For example, return to 201 and created successfully:
http_response_code(201);
Or use header to set:
header('HTTP/1.1 201 Created');
For common error responses, such as 400, 401, 403, 404, 500, you can flexibly set according to business needs.
Here is a complete API response sample code:
<?php
// set up JSON Response header
header('Content-Type: application/json; charset=utf-8');
// set up跨域
header('Access-Control-Allow-Origin: https://m66.net');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// Disable cache
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// return 200 Status code
http_response_code(200);
// return JSON data
$response = [
'status' => 'success',
'message' => 'API Response successfully',
'data' => ['id' => 1, 'name' => '测试data']
];
echo json_encode($response);
?>
Related Tags:
API