You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Step 1: Set Up Controlled Components

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.

Step 2: Add a Submission Handler

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).

Full Working Code
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;
Key Notes to Make This Work
  • Adjust the API URL: Replace http://55.5.555.555/login with the actual endpoint path on your server (e.g., /api/auth/login if 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 use user instead of username, etc.).
  • CORS Configuration: If your React app is running on a different domain/port than your server (e.g., React on localhost:3000, server on 55.5.555.555), you'll need to enable CORS on your server. This involves adding headers like Access-Control-Allow-Origin to 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-Type to application/x-www-form-urlencoded and using new URLSearchParams({ username: un, password: pwd }) as the body.

内容的提问来源于stack exchange,提问作者user8490655

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:48:13