Angular 2 - HTTP基本身份验证请求无法输入详细信息

时间:2017-03-30 14:51:30

标签: javascript angular http authentication authorization

我一直在尝试多种方法来访问使用基本身份验证的API。问题是Angular 2无法输入用户名和密码。

如果您导航到基本的身份验证网站,它会要求您输入用户名和密码,然后在大多数浏览器中点击Log InCancel。如果您点击此网站上的取消,它将返回一个字符串User pressed Cancel,这正是我通过Angular的HTTP请求获得的。

在这个阶段,Authorization标头中的编码用户名和密码是否正确无关紧要,我只需要能够发送用户名和密码并让它尝试登录。

有什么建议吗?

request() {
        let headers = new Headers();
        headers.append('Authorization', "Basic dWRpZDM6cGFzc3dvcmQ=");

        this.http.get('http://localhost:8888/api/', {
            headers: headers
        })
            .subscribe(
                data => this.example = data.text(),
                err => this.logError(err.text()),
                () => console.log('Request Complete')
            );
        console.log(this.example);
    }

2 个答案:

答案 0 :(得分:5)

使用用户名&添加授权密码应该有帮助。请尝试以下方法:

  _renderButton(title, onPress, active) {
    var style = (active) ? styles.activeButtonText : styles.buttonText;

    return (
      <TouchableHighlight style={styles.button} onPress={onPress}>
        <Text style={style}>
          {title}
        </Text>
      </TouchableHighlight>
    );
  }

  render() {

    return (
      <View style={styles.container}>
        <View style={styles.controls}>
           {this._renderButton("LISTEN", () => {this._playOriginalAudio()})}
           {this._renderButton(this.state.recordingText, () => {this._record()}, this.state.recording )}
           {this._renderButton("LISTEN TO RECORDING", () => {this._play()} )}
           {this._renderButton("SUBMIT", () => {this._send()} )}
        </View>
      </View>
      );
    }
  }

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#2b608a",
  },
  controls: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
  button: {
    padding: 20
  },
  disabledButtonText: {
    color: '#eee'
  },
  buttonText: {
    fontSize: 20,
    color: "#fff"
  },
  activeButtonText: {
    fontSize: 20,
    color: "#B81F00"
  },
  points: {
    backgroundColor: 'transparent',
    position: 'absolute',
    top: 72,
    left: 56,
    width: 90,
    textAlign: 'center',
    color: '#69d2e7',
    fontSize: 50,
    fontWeight: "100"
  },
  headerText: {
    paddingBottom: 10,
    fontSize: 20,
    color: "#69d2e7"
  }

});

希望这有帮助。

答案 1 :(得分:0)

问题实际上根本没有Angular 2或JS,标题已被附加和发送。但Apache没有将HTTP_AUTHORIZATION传递给PHP。

要解决此问题,我必须在API目录的.htaccess中设置以下内容:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

然后我必须手动设置PHP_AUTH_USERPHP_AUTH_PW

list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
$data = array();

另一个解决方法是在本地创建一个PHP或Node.js包装器,并将参数从angular发送到该页面,然后使用该页面发出CURL请求,该请求也有效。

相关问题