在 react 中使用 Fetch,需要用户名密码才能访问数据库

2022-01-20 00:00:00 reactjs fetch php mysql

我已经对此进行了数小时的研究,但找不到我需要的答案.抱歉,如果有人问过这个问题并且我的研究一直很糟糕,如果是这样,只需链接有用的堆栈溢出页面,我就会快乐地走下去.这是我的问题的摘要.

I have done hours of research on this and just can't find the answer I need. Sorry if this has been asked and I have been bad in my research, if so just link the helpful stack overflow page and I'll be on my merry way. Here is the summary of my problem.

我在 CS4 班,我们正在设计自己的网页,必须使用我们学校的服务器进行数据库存储.我们学习了 php 以及如何使用 mySQL,我们对服务器的 POST 和 GET 请求看起来像这样(用 PHP 编写):

I am in a CS4 class and we are designing our own webpage and must use our school's server for database storage. We learned php and how to use mySQL and our POST and GET requests for the server would look like this (written in PHP):

require("config.php");

$db = new PDO("mysql:dbname=" . $GLOBALS["database"] . ";host=" . $GLOBALS["hostname"] . ";port=" . $GLOBALS["port"], 
$GLOBALS["username"], $GLOBALS["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM Karrsen_ajaxtest"; 
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
    print(strip_tags($row['name']) . "<br/>");
}

配置正确设置的地方.

现在我正在做我的最后一个项目 React.js 并且必须从同一服务器请求.我想使用内置的 Fetch 系统,但它会引发 CORS 错误,而且我也不知道如何添加上述用户名、密码、数据库和主机名.我已经彻底查看了 MDN 网络文档(认为它可能是请求标头、凭据、模式或完整性?),但除了它说是否必须将自己添加到服务器上的 Access-Control-Allow-Origin 之外没有发现太多(但我无法编辑学校服务器的设置.)

Now I am doing my final project it React.js and have to request from the same server. I want to use the built in Fetch system but it throws CORS errors and I also don't know how to add the aforementioned username, password, database, and hostname. I have looked through the MDN webdocs thoroughly (thought it might be request Header, Credentials, Mode, or Integrity?) but didn't find much besides it saying if have to add myself to Access-Control-Allow-Origin on the server (but I cannot edit the settings of my school server.)

如何添加这些凭据?我会继续收到 CORS 错误吗?抱歉,如果这是浪费您的时间,请不要对堆栈溢出了解太多

How do I add these credentials? Will I continue to get a CORS error. Sorry if this is a waste of your time, don't know too much about stack overflow

*编辑我有我的反应应用程序,其中我现在唯一的组件将是一些登录内容.它被称为 Login.JS.现在我想做的就是在提交表单时从数据库中获取数据.这是我的代码.

*EDIT I have my react app in which my only component right now will be some login stuff. It is called Login.JS. Right now all I want it to do is get the data from the database on submit of the form. Here is my code.

import React from 'react';

class Login extends React.Component{
  constructor (props) {
    super(props);

    this.state = {
        userName: "",
        password: "",
        hits: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = event => {
    this.setState({
        [event.target.name]: event.target.value
    });
  }

  handleSubmit(e) {
    console.log(e);
    e.preventDefault();
    this.updateFromDB();
  }

  formValidation() {
    return this.state.password.length > 0 && this.state.userName.length > 0;
  }

  updateFromDB(){
    let API = "THE_URL_FOR_MY_DATABASE";
    let query = "SELECT * FROM karrsen_test";
    fetch(API + query, {
        method: 'POST',
        mode: 'cors'
    })
    .then(response => response.json())
    .then(data => this.setState({ hits: data.hits }));
  }

  render (){
    return(
        <div className= "Login-form">
            <form onSubmit = {(e) => this.handleSubmit(e)}>
                <label>
                    Username:
                    <input 
                    type = "text" 
                    value = {this.state.userName} 
                    onChange = {this.handleChange} 
                    name = "userName"/>
                </label>
                <label> 
                    Password:
                    <input
                    type = "text"
                    value = {this.state.password}
                    onChange = {this.handleChange}
                    name = "password" />
                </label>
                <input 
                    disabled = {!this.formValidation()}
                    type = "submit" />
            </form>
        </div>
    )

  }
}

export default Login;

推荐答案

CORS 由 default 与 fetch,但您的服务器需要配置为处理跨源请求.

CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.

假设您学校的服务器正在运行 Apache,您应该能够通过将 .htaccess 文件添加到您的 PHP 目录来做到这一点.只需将文件命名为 .htaccess 并添加以下行.

Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.

Header set Access-Control-Allow-Origin "*"

这需要将 Apache 服务器配置为允许在 DocumentRoot 中进行覆盖.DocumentRoot 是 Apache 托管的根目录.例如,假设您从 /var/www/example 目录托管 example.com./var/www/example 是 DocumentRoot.

This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.

在 example.com 的 Apache 配置中,必须设置 AllowOverride 指令以允许 .htaccess 文件覆盖基本配置 - 否则 .htaccess 文件被忽略.

In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.

要使 Apache 能够控制和修改 HTTP 请求和响应标头,必须启用 mod_headers 模块.从终端输入以下命令.

To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.

a2enmod headers

如果一切都失败了,您可以尝试使用 PHP 编辑响应(来自服务器)HTTP 标头,方法是将以下行添加到您的 PHP 脚本中 - 可能在其他任何内容之前位于顶部.

If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.

header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");

相关文章