react.jsでログインを構築し、それを私のspringbootに接続しようとしています。反応し、要求ステータスが正しくありません400.必須の文字列パラメータ 'login'が存在しません
@RestController
public class TestController {
@RequestMapping(value = "/test/login", method = RequestMethod.GET)
public Boolean testLogin(@RequestParam String login, @RequestParam String password) {
if (login.equals ("ajt"))
return true;
else {
return false;
}
}
それらのそれぞれは、2つの異なるポートに存在している:ここでは
は私のコード、react.jsです:import React from 'react';
export default class Login extends React.Component {
constructor() {
super();
this.state = {
login:"",
password:""
}
}
// This will be called when the user clicks on the login button
login(e) {
e.preventDefault();
console.log(this.state.password)
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('POST', "http://localhost:8080/test/login");
if (!xhr) {
throw new Error('CORS not supported');
}
fetch().then(r => r.json())
.then(data => console.log(data))
.catch(e => console.log(e))
}
render() {
return (
<form role="form">
<div>
<input type="text" name="login" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
</div>
<button type="submit"onClick={this.login.bind(this)}>Login</button>
</form>
);
}
}
そして、これはTestControllerように配置され、私のspringbootコードですon:9000、springboot on:8080。私がページを反応させるに
はまた、私はエラーを取得する:
TypeError: Failed to execute 'fetch' on 'Window': 1 argument required, but only 0 present.(…)
任意のアイデア?
info:私は6ヶ月間私の後ろにコーディングしています-_-親切にしてください!
です。文字列パラメータのログインが存在しないため、春のアプリケーションでコード400を取得しました。 react.jsアプリケーションに 'Preflight Requestへの応答がアクセス制御を渡していないことを確認します。 'というチェックボックスが表示されます。要求されたリソースに' Access-Control-Allow-Origin 'ヘッダーがありません。したがって、 'http:// localhost:9000'はアクセスが許可されていません。応答はHTTPステータスコード403でした。私の理解では、春にはログインパラメータを受け取ることができないが、反応は春に見えるが投稿できない。 –
あなたが直面していることは、CORSの問題です。デフォルトでは、作成したものから来ていない限り、サーバーはアクセスできません。これはいい。誰かがあなたのシステムにログイン要求を送ることを許可するプログラムを書くことを他人に嫌っています。ただし、あなたの反応とapiのコンポーネントは異なるホスト(locahost:8080対localhost:9000)でホストされているため、問題です。これを修正するには、localhost:9000からの着信要求を許可するようにAPIに指示する必要があります。 '@CrossOrigin(originins =" http:// localhost:9000 ")' – gravityplanx
私は実際に誰かによって提出されたCORSFilterを介してこの問題を克服しました(私はそのオプションを試しました。だから、私はreactjsアプリから提出すると、エラー400(OK)が赤色になりますが、これはSpringアプリケーションからコンソールを起動し、 'Required String parameter 'login' not present'をトリガーします。だから私は今彼らが接続されていると感じるが、情報が反応によってうまく送信されないか、春からの受信がうまくコーディングされていないことを意味する。 –