无法让代理服务器在本地 mysql 数据库的 React 应用程序上工作

Can't get a proxy server working on react app for local mysql database

我是 react/dev 的新手,所以我可能是个白痴。我有一个本地 mySQL 数据库,我正在尝试使用快速服务器将数据从我的前端 React 应用程序中提取出来。

我已将服务器设置为:

// This is the routes.js file!

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const connection = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'asdf'
});

// Starting our app.
const app = express();

// Creating a GET route that returns data from the 'xxxx' table.
app.get('/xxxx', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

    // Executing the MySQL query (select all data from the 'xxxx' table).
    connection.query('SELECT * FROM xxxx', function (error, results, fields) {
      // If some error occurs, we throw an error.
      if (error) throw error;

      // Getting the 'response' from the database and sending it to our route. This is were the data is.
      res.send(results)
    });
  });
});

// Starting our server.
app.listen(process.env.PORT || 8080);

向 package.json 文件添加了代理:

.....
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "proxy": "http://localhost:8080",
  "scripts": {
    "start": "react-scripts start",
......

并在我的 app.js

中调用了它
  componentDidMount() {
    fetch('http://localhost:8080/xxxx')
      .then(response => response.json())
      .then(xxxx=> this.setState({ xxxx }, () => console.log("successfully fetched xxxx", xxxx)));
  }

但是我仍然收到以下错误:

Access to fetch at 'http://localhost:8080/xxxx' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

代理不应该阻止这个吗?我做错了什么(我可以在 localhost:8080/xxxx 看到所有数据)

因为您在 package.json 中指定了代理,当您从客户端向服务器发出请求时,您希望省略 url 的原始部分。

这应该改为

  componentDidMount() {
    fetch('http://localhost:8080/xxxx')
      .then(response => response.json())
      .then(xxxx=> this.setState({ xxxx }, () => console.log("successfully fetched xxxx", xxxx)));
  }

这个

    fetch('/xxxx')
      .then(response => response.json())
      .then(xxxx=> this.setState({ xxxx }, () => console.log("successfully fetched xxxx", xxxx)));
  }

基本上你只会指定实际的端点并离开原点,这现在将允许 webpack 开发服务器将你的请求代理到你的快速服务器。

Chaim 上面的回答有效!谢谢