axios 代理错误:无法将请求/auth/register从本地主机3000代理到http://localhost:8800/api/

1rhkuytd  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(240)

register.jsx

import React from 'react'
import { useState } from "react";
import {Link } from 'react-router-dom'
import axios from "axios";

const Register = () => {
const [inputs,setInputs] = useState({
  username:"",
  email:"",
  password:"",
})
const [err, setError] = useState(null)
const handleChange = e =>{
  setInputs(prev=>({...prev, [e.target.name]: e.target.value}))
}

const handleSubmit = async e =>{
  e.preventDefault()
//  try{
   const res = await axios.post("/auth/register", inputs)
console.log ("test",res)
// }catch(err){
  // console.log("test",err.response.data)
  // }
}

  return (

    <div className='auth'>
        <h1>Register</h1>
        <form>
            <input required type="text" placeholder='username' name='username' onChange={handleChange}/> 
            <input required type="email" placeholder='email' name='email' onChange={handleChange}/>
            <input required type="password" placeholder='password' name='password' onChange={handleChange}/>
            <button onClick={handleSubmit} >Register</button>
            {err &&<p>{err}</p>}
            <span>Do you have an account? <Link to="/login">Login</Link>
            </span>
        </form>
    </div>
  );
}

export default Register

auth.js

import { db } from "../db.js";
import bcrypt from "bcryptjs";

export const register = (req, res) => {
    //CHECK EXISTING USER
    const q = "SELECT * FROM users WHERE email = ? OR username = ?";
  
    db.query(q, [req.body.email, req.body.username], (err, data) => {
      if (err) return res.status(500).json(err);
      if (data.length) return res.status(409).json("User already exists!");
  
      //Hash the password and create a user
      const salt = bcrypt.genSaltSync(10);
      const hash = bcrypt.hashSync(req.body.password, salt);
  
      const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
      const values = [req.body.username, req.body.email, hash];
  
      db.query(q, [values], (err, data) => {
        if (err) return res.status(500).json(err);
        return res.status(200).json("User has been created.");
      });
    });
  };

export const login = (req, res) ={};
export const logout = (req, res) ={};

package.json

{
  "name": "booking",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "dompurify": "^2.4.0",
    "moment": "^2.29.4",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-quill": "^2.0.0",
    "react-router-dom": "^6.4.1",
    "react-scripts": "5.0.1",
    "sass": "^1.55.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800/api/"
}

我正在学习教程https://www.youtube.com/watch?v=0aPLk2e2Z3g&t=3250s
我被这个错误卡住了:代理错误:无法将请求/auth/register从本地主机3000代理到http://localhost:8800/api/。有关详细信息,请访问www.example.com(ECONNREFUSED)。https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
请帮帮忙
我试了网上的一切都没有工作

68bkxrlz

68bkxrlz1#

看看Proxying API Requests in Development,当你在package.json中定义React服务器代理时,它不应该像你那样在末尾(/api)包含路径名,它应该看起来像:
"proxy": "http://localhost:8800",
它还假设您使用的是/api/*请求,在您的示例中,您使用的是/auth/*
我推荐使用client/src/setupProxy.js文件,这样你就可以定义多个代理到后端的路径:

const { createProxyMiddleware } = require('http-proxy-middleware');

const proxy_urls = ['/api/*', '/auth/*'];

const target = 'http://localhost:8800';

module.exports = function (app) {
  proxy_urls.forEach((url) => {
    app.use(url, createProxyMiddleware({ target }));
  });
};

相关问题