使用Fetch in react,需要用户名密码才能访问数据库 [英] Using Fetch in react, need username password to access database

查看:96
本文介绍了使用Fetch in react,需要用户名密码才能访问数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了数小时的研究,只是找不到我需要的答案.抱歉,如果有人问过这个问题,而我的研究一直很糟糕,那么请链接有用的堆栈溢出页面,我会很乐意.这是我的问题的摘要.

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 Webdocs(可能是请求标头,凭证,模式还是完整性?),但除了发现是否必须将自己添加到服务器上的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

*编辑 我有我的react应用程序,其中我现在唯一的组件将是一些登录内容.它称为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由

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

假设您学校的服务器运行的是Apache,那么应该可以通过向PHP目录中添加.htaccess文件来做到这一点.只需将文件命名为.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']}");

这篇关于使用Fetch in react,需要用户名密码才能访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆