调用GET接口获取iframe的src链接时返回Bad Request错误的求助
Let's break down the two main issues in your code and how to fix them:
1. Incorrect Async Handling for the Iframe URL
Right now, srcUrl is a Promise object (not the actual URL string) because getJobView() returns a promise. The iframe's src prop expects a valid URL string, so this will never work as intended. Here's how to fix this using component state:
Step 1: Add State to Track the URL & Request Status
In your class component, initialize state to manage the fetched URL, loading state, and errors:
state = { jobViewUrl: null, isLoading: false, fetchError: null };
Step 2: Fetch the URL Asynchronously
Add a method to fetch the URL when the component mounts (or when the modal is triggered):
fetchJobViewUrl = async () => { this.setState({ isLoading: true, fetchError: null }); try { const response = await getJobView(); // Update this line to match your API's response structure (e.g., response.data.src) this.setState({ jobViewUrl: response.data, isLoading: false }); } catch (err) { console.error("Failed to load job view URL:", err.response?.data || err.message); this.setState({ fetchError: err.message, isLoading: false }); } }; // Call this method when the component mounts or when the modal opens componentDidMount() { this.fetchJobViewUrl(); }
Step 3: Update the Modal Content Rendering
Modify your modalContent method to render based on the state:
modalContent = () => { const { classes } = this.props; const { jobViewUrl, isLoading, fetchError } = this.state; if (isLoading) { return <Paper className={classes.modalPaper}>Loading job view...</Paper>; } if (fetchError) { return <Paper className={classes.modalPaper}>Error: {fetchError}</Paper>; } return ( <Paper className={classes.modalPaper}> {jobViewUrl && ( <iframe src={jobViewUrl} style={{ width: '800px', height: '800px' }} title="Job View" frameBorder="0" ></iframe> )} </Paper> ); };
2. Fixing the Bad Request Error
A 400 Bad Request usually means your API call is missing required data or headers. Here are common fixes:
Add Authentication Headers: If your API requires a token, include it in the request headers:
// In your getJobView function const options = { method: 'GET', headers: { 'content-type': 'application/json', 'Authorization': `Bearer ${yourAuthToken}` // Replace with your actual token }, url: `${BASE_API_ROOT}/level2` };Verify the API URL: Double-check that
BASE_API_ROOTis correct (e.g., no trailing slashes that break the endpoint path). Log the full URL to confirm:console.log("Full API URL:", `${BASE_API_ROOT}/level2`);Check for Required Query Parameters: Some GET endpoints require parameters (like a job ID). Add them if needed:
url: `${BASE_API_ROOT}/level2?jobId=${this.props.jobId}` // Example parameterRemove Unnecessary Headers: For GET requests, the
content-typeheader is often unnecessary. Try removing it to see if that resolves the error.Inspect the Error Response: Modify your catch block to get more details about the failure:
catch (err) { console.error("API Error Details:", err.response); // Shows status code, error message from server }
Content of the question来源于stack exchange,提问作者Kenny Quach

