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

AngularJS新手开发登录功能遇[$http:baddata]错误求助

Fixing the [$http:baddata] Error in Your Angular Login Flow

Hey there! Let's break down this [$http:baddata] error you're seeing—it's super common when pairing Angular with PHP, so don't stress. Here's exactly what's going on and how to fix it step by step:

What's Causing the Error?

That error means Angular's $http service tried to parse the response from your PHP backend as JSON... but got HTML instead. Look at the error snippet: you can see <br> and Fatal error tags—your PHP script is throwing a fatal error and spitting out an HTML error page, not the valid JSON Angular expects.


Step 1: Fix Your PHP Backend to Return Valid JSON

First, we need to make sure your PHP script stops throwing errors and always sends back proper JSON, even when something goes wrong. Here's a secure, error-handled example you can adapt:

<?php
// Turn off visible error output (we'll log errors instead)
error_reporting(0);
ini_set('display_errors', 0);
// Enable error logging to a file (check this file if you need to debug)
ini_set('log_errors', 1);
ini_set('error_log', './login_errors.log');

// Connect to your database (update these values!)
$dbHost = 'localhost';
$dbUser = 'your_db_user';
$dbPass = 'your_db_password';
$dbName = 'your_db_name';

$conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);

// Handle database connection failure
if (!$conn) {
    echo json_encode([
        'success' => false,
        'message' => 'Could not connect to database'
    ]);
    exit;
}

// Get login data from Angular (Angular sends JSON, so we read from php://input)
$rawInput = file_get_contents('php://input');
$loginData = json_decode($rawInput, true);

$username = $loginData['username'] ?? '';
$password = $loginData['password'] ?? '';

// IMPORTANT: Use prepared statements to prevent SQL injection!
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();
    // Verify password (ALWAYS use password_hash()/password_verify() in production!)
    // If you stored plain text (don't do this!), replace with: if ($password === $user['password'])
    if (password_verify($password, $user['password'])) {
        echo json_encode([
            'success' => true,
            'message' => 'Login successful'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid username or password'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid username or password'
    ]);
}

// Clean up connections
$stmt->close();
$conn->close();
?>

Critical Note: Never store plain-text passwords! Use PHP's password_hash() when creating user accounts, and password_verify() (like above) to check passwords. This example uses secure practices to keep your app safe.


Step 2: Update Your Angular $http Request

Make sure your Angular controller sends data in the right format and handles the JSON response correctly. Here's a sample controller:

angular.module('LoginApp', [])
.controller('LoginCtrl', ['$http', '$location', function($http, $location) {
    const vm = this;

    vm.submitLogin = function() {
        const loginPayload = {
            username: vm.username,
            password: vm.password
        };

        $http.post('path/to/your/login.php', loginPayload)
            .then(function(response) {
                // Success: Check if login was valid
                if (response.data.success) {
                    // Redirect to dashboard
                    $location.path('/dashboard');
                } else {
                    // Show error message to user
                    alert(response.data.message);
                }
            })
            .catch(function(error) {
                // Handle request failures or invalid JSON
                console.error('Login error:', error);
                alert('Something went wrong—check your backend logs!');
            });
    };
}]);

And your HTML login form might look like this:

<div ng-app="LoginApp" ng-controller="LoginCtrl as login">
    <input type="text" ng-model="login.username" placeholder="Username">
    <input type="password" ng-model="login.password" placeholder="Password">
    <button ng-click="login.submitLogin()">Login</button>
</div>

Step 3: Debug Any Remaining PHP Errors

If you still get the baddata error, check the login_errors.log file we set up in the PHP script—it will tell you exactly what's causing the fatal error (like a missing database table, syntax mistake, or wrong credentials). Fix those issues first, and your PHP script will start returning valid JSON.


Once your PHP backend consistently sends valid JSON responses (whether login succeeds or fails), Angular will be able to parse the data correctly, and the [$http:baddata] error will disappear.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:20:31