Using Fetch in react, need username password to access database

淺唱寂寞╮ 提交于 2019-12-23 16:56:51

问题


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.

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/>");
}

Where the config was set correctly.

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.)

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

*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;

回答1:


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

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 "*"

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.

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.

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

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']}");


来源:https://stackoverflow.com/questions/53384998/using-fetch-in-react-need-username-password-to-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!