Home >Web Front-end >uni-app >How do I use uni-app's uni.request API for making HTTP requests?
The uni.request
API in uni-app is a versatile tool for making HTTP requests to various servers. It's a wrapper around the native XMLHttpRequest object, providing a more convenient and cross-platform approach. Here's a detailed breakdown of how to use it:
Basic Usage:
The core function is uni.request()
, which takes an options object as its argument. This object specifies the request details. A simple GET request might look like this:
<code class="javascript">uni.request({ url: 'https://api.example.com/data', method: 'GET', success: (res) => { console.log('Request successful:', res.data); }, fail: (err) => { console.error('Request failed:', err); }, complete: (res) => { console.log('Request completed:', res); } });</code>
This code sends a GET request to https://api.example.com/data
. The success
callback handles successful responses, fail
handles errors, and complete
executes regardless of success or failure. res.data
contains the response data.
Advanced Options:
uni.request
supports various options for customizing your requests:
method
: Specifies the HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to GET.data
: The data to send with the request (usually for POST, PUT, etc.). This can be an object or a string.header
: An object containing HTTP headers (e.g., Content-Type
, Authorization
).dataType
: Specifies the expected data type of the response ('json' is common).responseType
: Specifies the expected response type ('text', 'arraybuffer', etc.).timeout
: Sets a timeout for the request in milliseconds.Example POST request:
<code class="javascript">uni.request({ url: 'https://api.example.com/submit', method: 'POST', header: { 'Content-Type': 'application/json' }, data: { name: 'John Doe', email: 'john.doe@example.com' }, success: (res) => { // ... }, fail: (err) => { // ... } });</code>
Robust error handling is crucial for a smooth user experience. Here are common techniques for handling errors with uni.request
:
fail
Callback: The fail
callback is the primary mechanism. It receives an error object containing information about the failure (e.g., status code, error message). Use this to provide informative error messages to the user or log the error for debugging.fail
callback (or even in complete
for more comprehensive handling). Different status codes indicate different issues (404 Not Found, 500 Internal Server Error, etc.). Handle these cases differently, providing tailored user feedback.uni.request
might fail due to a lack of internet connection. You can use uni.getSystemInfoSync().networkType
to check the network status before making the request or handle network errors specifically within the fail
callback.uni.request
which already provides callbacks, you could wrap the uni.request
call in a try...catch
block to catch unexpected errors that might occur outside the request itself (e.g., JSON parsing errors).Example with status code checking:
<code class="javascript">uni.request({ // ... request options ... fail: (err) => { if (err.statusCode === 404) { uni.showToast({ title: 'Resource not found', icon: 'error' }); } else if (err.statusCode === 500) { uni.showToast({ title: 'Server error', icon: 'error' }); } else { uni.showToast({ title: 'An error occurred', icon: 'error' }); console.error('Request failed:', err); } } });</code>
Integrating uni.request
with an authentication system typically involves adding an Authorization header to each request. This header usually contains a token (JWT, session ID, etc.) that identifies the authenticated user.
Implementation:
uni.setStorageSync
and uni.getStorageSync
).header
object:<code class="javascript">const token = uni.getStorageSync('token'); uni.request({ url: 'https://api.example.com/protected-data', header: { 'Authorization': `Bearer ${token}` // Adjust as needed for your auth scheme }, success: (res) => { // ... }, fail: (err) => { // Handle authentication errors (e.g., 401 Unauthorized) if (err.statusCode === 401) { // Redirect to login or refresh token } } });</code>
Yes, uni.request
can upload files, but it requires using the formData
API. Here's how:
Implementation:
FormData
object and append the file to it. You'll need to access the file using the appropriate uni-app file selection API (e.g., uni.chooseImage
or uni.chooseVideo
).Content-Type
header to multipart/form-data
.FormData
object as the data
.Example:
<code class="javascript">uni.chooseImage({ count: 1, success: (res) => { const filePath = res.tempFiles[0].path; const formData = new FormData(); formData.append('file', { uri: filePath, name: 'file.jpg', // Adjust filename as needed type: 'image/jpeg' // Adjust file type as needed }); uni.request({ url: 'https://api.example.com/upload', method: 'POST', header: { 'Content-Type': 'multipart/form-data' }, data: formData, success: (res) => { // ... }, fail: (err) => { // ... } }); } });</code>
Remember to adjust the name
and type
properties according to your uploaded file. The server-side needs to be configured to handle multipart/form-data
uploads. Also, consider using a progress indicator to show upload progress to the user for a better user experience, which usually requires a different approach beyond the basic uni.request
.
The above is the detailed content of How do I use uni-app's uni.request API for making HTTP requests?. For more information, please follow other related articles on the PHP Chinese website!