简体   繁体   English

header("访问控制允许来源:"); 不工作 CORS 策略,预检请求不允许重定向

[英]header("Access-Control-Allow-Origin: "); dont work CORS policy, Redirect is not allowed for a preflight request

I have tried many things but I keep getting an error.我已经尝试了很多事情,但我不断收到错误消息。 I try to fix我尝试修复

Access to fetch at 'http://mysite.nl/login.php' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." CORS 策略已阻止从源“http://localhost:19006”获取“http://mysite.nl/login.php”的访问权限:对预检请求的响应未通过访问控制检查:重定向未通过允许预检请求。”

Now I read this file:现在我读了这个文件:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

It's hard to understand because I'm a beginner很难理解,因为我是初学者

And add to my php file:并添加到我的 php 文件中:

header("Access-Control-Allow-Origin: **http://mywebsite.nl/login.php**");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

( "http://mywebsite.nl/login.php" , I changed my website name to mywebsite) ( "http://mywebsite.nl/login.php" , 我把网站名改成了 mywebsite)

<?php
include('db.php');

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$UserEmail = $decodedData['Email'];
$UserPW = ($decodedData['Password']); //password is hashed

$SQL = "SELECT * FROM newuser WHERE UserEmail = '$UserEmail'";
$exeSQL = mysqli_query($conn, $SQL);
$checkEmail =  mysqli_num_rows($exeSQL);

if ($checkEmail != 0) {
    $arrayu = mysqli_fetch_array($exeSQL);
    if ($arrayu['UserPw'] != $UserPW) {
        $Message = "pw WRONG";
    } else {
        $Message = "Success";
    }
} else {
    $Message = "No account yet";
}

$response[] = array("Message" => $Message);
echo json_encode($response);

This is my signin.js file.这是我的 signin.js 文件。

import React, { Component } from 'react';
import { View, Pressable, Text, TextInput, TouchableOpacity, Button} from 'react-native';
import stylesin from '../../style';
import Feather from 'react-native-vector-icons/Feather';

export default class signin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email : '',
      password : '',
      check_textInputChange : false,
      secureTextEntry : true,
    };
  }

  InsertRecord=()=>{
    var Email = this.state.email;
    var Password = this.state.password;

    if ((Email.length==0) || (Password.length==0)){
      alert("Required Field Is Missing!!!");
    }else{
      var APIURL = **"http://mywebsite.nl/login.php"**;

      var headers = {
        'Accept' : 'application/json',
        'Content-Type' : 'application/json'
      };
            
      var Data ={
        Email: Email,
        Password: Password
      };

      fetch(APIURL,{
        method: 'POST',
        headers: headers,
        body: JSON.stringify(Data)
      })
      .then((Response)=>Response.json())
      .then((Response)=>{
        alert(Response[0].Message)
        if (Response[0].Message == "Success") {
          console.log("true")
          this.props.navigation.navigate("HomeScreen");
        }
        console.log(Data);
      })
      .catch((error)=>{
        console.error("ERROR FOUND" + error);
      })
    }
  }

  updateSecureTextEntry(){
    this.setState({
      ...this.state,
      secureTextEntry: !this.state.secureTextEntry
    });
  }

  render() {
    return (
      <View style={stylesin.viewStyle}>
          <View style={stylesin.action}>
            <TextInput
              placeholder="Enter Email"
              placeholderTextColor="#ff0000"
              style={stylesin.textInput}
              onChangeText={email=>this.setState({email})}
              />
          </View>

          <View style={stylesin.action}>
            <TextInput
              placeholder="Enter Password"
              placeholderTextColor="#ff0000"
              style={stylesin.textInput}
              secureTextEntry={this.state.secureTextEntry ? true : false}
              onChangeText={password=>this.setState({password})}
              />
                <TouchableOpacity
                  onPress={this.updateSecureTextEntry.bind(this)}>
                  {this.state.secureTextEntry ?
                  <Feather
                  name="eye-off"
                  color="grey"
                  size={20}
                  />
                :  
                  <Feather
                  name="eye"
                  color="black"
                  size={20}
                  />
                }
                </TouchableOpacity>  
          </View>


                {/* Button */}

                <View style={stylesin.loginButtonSection}>    
                  <Pressable
                    style={stylesin.loginButton} 
                    onPress={()=>{
                      this.InsertRecord()
                    }}
                    >
                      <Text style={stylesin.text}>Sign In</Text>
                  </Pressable>
                </View>

                <View style={stylesin.loginButtonSection}>
                  <Pressable
                    style={stylesin.loginButton} 
                    onPress={()=>{
                      // this.InsertRecord()
                    }}
                    >
                      <Text style={stylesin.text}>Create new Account</Text>
                    </Pressable>
                  </View>
      </View>
    );
  }
}

I read so many solutions that I don't understand it anymore.我阅读了很多解决方案,以至于我不再理解它了。

I had the same problem and I solved it with two functions and a configuration on the server.我遇到了同样的问题,我通过服务器上的两个功能和一个配置解决了这个问题。 Stop suffering and read this small solution: php-cors停止痛苦并阅读这个小解决方案: php-cors

Php CORS CORS To basically understand what cors are, I suggest that we see them as a mechanism used by clients such as browsers or any other interface that makes http requests to validate if the source of the request is compatible with the destination. Php CORS CORS To basically understand what cors are, I suggest that we see them as a mechanism used by clients such as browsers or any other interface that makes http requests to validate if the source of the request is compatible with the destination. This compatibility is defined by means of limitations or policies from the server or origin.这种兼容性是通过来自服务器或源的限制或策略来定义的。 If you want to know a more complete and technical definition, consult in: HTTP Access Control (CORS)如果您想了解更完整的技术定义,请参阅:HTTP 访问控制 (CORS)

The following solution is to enable CORS in PHP using two functions:以下解决方案是使用两个函数在 PHP 中启用 CORS:

  • enableCors: Depending on your logic the call of this function would be done at the beginning of the execution, its scope is to detect the previous request of some clients such as browsers among others. enableCors:根据您的逻辑,此 function 的调用将在执行开始时完成,其 scope 用于检测某些客户端(例如浏览器等)的先前请求。
  • cors: Returns an array with the configuration of the headers and the white list of sources that can make requests. cors:返回一个数组,其中包含标头的配置和可以发出请求的源的白名单。

Note: If you are using Nginx you will also need to allow the OPTIONS method or do a little trick to change a 405 http code response to 200:注意:如果您使用的是 Nginx,您还需要允许 OPTIONS 方法或做一些小技巧来将 405 http 代码响应更改为 200:

  • 1: Detect if the request method is OPTIONS and set some headers and http response code. 1:检测请求方法是否为OPTIONS并设置一些headers和http响应码。
  • 2: Define a value for the 405 error code response. 2:为 405 错误代码响应定义一个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “请求 header 字段 Access-Control-Allow-Origin 在预检响应中被 Access-Control-Allow-Headers 不允许”尽管 CORS 配置有效 - “Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response” despite valid CORS config 在执行预检请求时是否需要Access-Control-Allow-Origin CORS标头? - Is the Access-Control-Allow-Origin CORS header required when doing a preflight request? CORS 错误:对预检请求的响应 'Access-Control-Allow-Origin' header 包含多个值 '*、*'、 - CORS error: Response to preflight request The 'Access-Control-Allow-Origin' header contains multiple values '*, *', CORS 策略错误:“Access-Control-Allow-Origin”标头包含多个值“*”、“*”,但只允许一个 - CORS policy error: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed Cors 策略无访问控制允许来源' header - Cors Policy No Access-Control-Allow-Origin' header React+Express:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-origin - React+Express: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response 没有响应标头时允许CORS Access-Control-Allow-Origin - CORS allowed when no response header Access-Control-Allow-Origin 如何解决“Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? - How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? CORS飞行前返回Access-Control-Allow-Origin,但响应挂起 - CORS preflight return Access-Control-Allow-Origin but response hangs on CORS 策略已阻止从原点 '' 访问 XMLHttpRequest - Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM