React登录UI如何向本地服务器55.5.555.555提交用户名密码?
Hey there! Let's walk through fixing this POST request issue with your React login component. The main gaps in your current code are that your inputs aren't capturing user values (so you can't access the username/password) and there's no logic to send that data to your server via POST. Here's a complete, working implementation:
First, we need to bind your input fields to the component's state so we can track user input. This is called "controlled components" in React, and it lets us reliably access form values whenever we need them.
Next, we'll add a function to handle form submission, which will send the captured username and password to your server using the native fetch API (no extra dependencies required).
import React, { Component } from 'react'; class Login extends Component { constructor(props) { super(props); this.state = { un: "", pwd: "", loginError: "" // Track login errors to display to the user }; // Bind event handlers to the component instance this.handleInputChange = this.handleInputChange.bind(this); this.handleLoginSubmit = this.handleLoginSubmit.bind(this); } // Update state whenever the user types in an input handleInputChange(e) { const { name, value } = e.target; this.setState({ [name]: value }); } // Handle form submission and send POST request async handleLoginSubmit(e) { e.preventDefault(); // Stop the browser's default form reload behavior const { un, pwd } = this.state; try { const response = await fetch('http://55.5.555.555/login', { method: 'POST', headers: { 'Content-Type': 'application/json', // Tell the server we're sending JSON // Add any additional headers your server requires (e.g., API keys) here }, body: JSON.stringify({ username: un, // Match the key names your server expects (adjust if needed!) password: pwd }) }); // Check if the server responded successfully if (!response.ok) { throw new Error('Failed to log in. Please check your credentials.'); } // Parse the server's response (adjust based on what your server returns) const loginData = await response.json(); console.log('Login successful!', loginData); // Add your post-login logic here (e.g., redirect to dashboard, set auth tokens) } catch (error) { this.setState({ loginError: error.message }); console.error('Login error:', error); } } render() { const { un, pwd, loginError } = this.state; return ( <div className="login-container"> {/* Display error message if login fails */} {loginError && <p style={{ color: 'red' }}>{loginError}</p>} {/* Use a form element for proper submission behavior */} <form onSubmit={this.handleLoginSubmit}> <input type="text" name="un" // Matches the state key for username value={un} onChange={this.handleInputChange} placeholder="Username" required /> <input type="password" name="pwd" // Matches the state key for password value={pwd} onChange={this.handleInputChange} placeholder="Password" required /> <button type="submit">Submit</button> </form> </div> ); } } export default Login;
- Adjust the API URL: Replace
http://55.5.555.555/loginwith the actual endpoint path on your server (e.g.,/api/auth/loginif that's where your login route lives). - Match Server Expectations: Ensure the keys in
JSON.stringify({ username: un, password: pwd })match what your server is looking for (some servers might useuserinstead ofusername, etc.). - CORS Configuration: If your React app is running on a different domain/port than your server (e.g., React on
localhost:3000, server on55.5.555.555), you'll need to enable CORS on your server. This involves adding headers likeAccess-Control-Allow-Originto your server's responses (check your server framework's docs for how to set this up—e.g., Express, Django, etc.). - Alternative Request Formats: If your server doesn't accept JSON, you can send form data instead by changing the
Content-Typetoapplication/x-www-form-urlencodedand usingnew URLSearchParams({ username: un, password: pwd })as thebody.
内容的提问来源于stack exchange,提问作者user8490655

