React Native中用Axios通过POST请求获取LINNWORK API数据
Hey there! Let's walk through how to handle POST requests with Axios in your React Native app, especially focusing on the Linnworks API which requires an authentication step first.
Basic Axios POST with Headers & Credentials
First, let's cover the general approach for making a POST request with Axios, including custom headers like api-username, api-password, and apitoken. Here's how you can structure it in your component:
import axios from 'axios'; import { Component, View, Text } from 'react-native'; class DataFetcher extends Component { state = { responseData: [] }; componentDidMount() { // Define your custom headers const requestHeaders = { 'api-username': 'YOUR_API_USERNAME', 'api-password': 'YOUR_API_PASSWORD', 'apitoken': 'YOUR_API_TOKEN', 'Content-Type': 'application/json' // Adjust based on API requirements }; // Data to send in the POST body const postPayload = { // Add any parameters the API expects, e.g., filters, action types filter: 'active', limit: 10 }; // Make the POST request axios.post('YOUR_API_ENDPOINT_URL', postPayload, { headers: requestHeaders }) .then(response => { console.log('Success! Data:', response.data); this.setState({ responseData: response.data }); }) .catch(error => { console.error('Request failed:', error.response?.data || error.message); // Add user-facing error handling here, like an alert }); } render() { return ( <View> {this.state.responseData.map(item => ( <Text key={item.id}>{item.name}</Text> ))} </View> ); } } export default DataFetcher;
Key notes here:
- Axios's
postmethod takes three arguments: the API URL, the request body data, and a config object (where we pass headers). - Always set the correct
Content-Typeheader—most APIs expectapplication/jsonfor JSON payloads.
Linnworks API Authentication & Data Fetching
Since you're working with the Linnworks API, you'll need to handle authentication first before accessing other endpoints. Here's a step-by-step implementation:
Step 1: Fetch an Authorization Token
Linnworks requires you to get a valid token using your credentials (email, password) and your app ID (you'll need to register your app in the Linnworks Developer Portal first).
// Helper function to get auth token const getLinnworksAuthToken = async () => { try { const authResponse = await axios.post('https://api.linnworks.net/api/Auth/AuthorizeByCredentials', { Email: 'YOUR_LINNWORKS_EMAIL', Password: 'YOUR_LINNWORKS_PASSWORD', ApplicationId: 'YOUR_LINNWORKS_APP_ID' }); // Extract the token from the response (check Linnworks docs for exact field name) return authResponse.data.Token; } catch (error) { console.error('Authorization failed:', error.response?.data || error.message); throw new Error('Could not authenticate with Linnworks'); } };
Step 2: Use the Token to Fetch Data
Once you have the token, include it in your request headers for subsequent API calls. Here's how to integrate this into your component:
import { Alert } from 'react-native'; class LinnworksDataFetcher extends Component { state = { inventoryItems: [] }; componentDidMount() { this.fetchLinnworksInventory(); } async fetchLinnworksInventory() { try { // 1. Get auth token first const authToken = await getLinnworksAuthToken(); // 2. Set up headers with the token const requestHeaders = { 'apitoken': authToken, 'Content-Type': 'application/json' }; // 3. Make POST request to an example Linnworks endpoint (e.g., get inventory items) const inventoryResponse = await axios.post( 'https://api.linnworks.net/api/Inventory/GetInventoryItems', { PageNumber: 1, EntriesPerPage: 20, // Add any other required parameters here }, { headers: requestHeaders } ); this.setState({ inventoryItems: inventoryResponse.data }); } catch (error) { console.error('Failed to fetch inventory:', error.message); // Show an alert to the user if needed Alert.alert('Error', 'Could not load inventory data'); } } render() { // Render your inventory items here return ( <View> {this.state.inventoryItems.map(item => ( <Text key={item.ItemId}>{item.ItemTitle}</Text> ))} </View> ); } }
Important Linnworks API Tips
- Token Expiry: Linnworks tokens do expire—add logic to catch
401 Unauthorizederrors and re-fetch the token before retrying the request. - Environment Variables: Never hardcode credentials or tokens! Use a package like
react-native-dotenvto store sensitive data in environment variables. - Official Docs: Always refer to the Linnworks API documentation for exact endpoint URLs, required parameters, and header formats—they may change over time.
内容的提问来源于stack exchange,提问作者Jarnail S

