响应错误:【AxiosError:网络错误]

l7mqbcuq  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(151)

我收到这个响应错误:【AxiosError:网络错误]在我的React Native项目上。我正在尝试将React Native App与MySQL数据库连接。
我研究了很多,大多数开发者说它多是基础网址http://localhost:5000造成的;它应该遵循HTTP协议,但我已经添加了它,但仍然得到错误。
我已经安装了依赖项,包括
第一个月
npm install cors

auth.js

import axios from 'axios';

// Replace this with your backend server URL
const BASE_URL = 'http://localhost:5000';



// Function for user sign-up
const signUp = async (email, password, fullName) => {
  try {
    const response = await axios.post(`${BASE_URL}/signup`, { email, password, fullName });
    console.log(response.data); // Handle the response from the server
  } catch (error) {
    console.error(error); // Handle any errors that occur during the request
  }
};

// Function for user login
const login = async (email, password) => {
  try {
    const response = await axios.post(`${BASE_URL}/login`, { email, password });
    const token = response.data.token;
    console.log(token); // Use the token for subsequent authenticated requests
  } catch (error) {
    console.error(error); // Handle any errors that occur during the request
  }
};

export { signUp, login };

字符串

backend/index.js

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql2');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();
app.use(bodyParser.json());
app.use(cors());

// Replace these values with your MySQL database credentials
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'beba_connect',
});

// MySQL connection test
db.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL database:', err);
    return;
  }
  console.log('Connected to MySQL database');
});


// Sign-up route
app.post('/signup', (req, res) => {
  const { fullName, email, password } = req.body;

  // Hash the password before storing it in the database
  bcrypt.hash(password, 10, (err, hashedPassword) => {
    if (err) {
      console.error('Error hashing password:', err);
      res.status(500).json({ error: 'Internal server error' });
      return;
    }

    // Insert user data into the database
    const newUser = {fullName, email, password: hashedPassword };
    db.query('INSERT INTO users SET ?', newUser, (err) => {
      if (err) {
        console.error('Error inserting user:', err);
        res.status(500).json({ error: 'Internal server error' });
        return;
      }

      res.json({ message: 'User registered successfully' });
    });
  });
});

// Login route
app.post('/login', (req, res) => {
  const { email, password } = req.body;

  // Retrieve user data from the database based on the email
  db.query('SELECT * FROM users WHERE email = ?', [email], (err, results) => {
    if (err) {
      console.error('Error retrieving user:', err);
      res.status(500).json({ error: 'Internal server error' });
      return;
    }

    if (results.length === 0) {
      res.status(401).json({ error: 'User not found' });
      return;
    }

    const user = results[0];

    // Compare the password with the hashed password in the database
    bcrypt.compare(password, user.password, (err, isMatch) => {
      if (err) {
        console.error('Error comparing passwords:', err);
        res.status(500).json({ error: 'Internal server error' });
        return;
      }

      if (!isMatch) {
        res.status(401).json({ error: 'Invalid password' });
        return;
      }

    const secretKey = 'e604733c3ae40d201fe774c86ab1ec09e941eb48bba8fe31e9cccc8085ce058c';
     const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: '1h' });
      res.json({ token });
    });
  });
});

// Start the server
const port = 5000; // Change this to your preferred port
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});


我哪里做错了好心帮忙

3hvapo4f

3hvapo4f1#

你需要配置请求头类型= application/json

相关问题