'Bad Request when calling API from React.js with Keycloak Authorization
I am calling an API through my React.js file.
Here is the API endpoint I am calling:
[ApiController]
[Route("record")]
public class RecordController : Controller
{
[Route("addrecord")]
[HttpPost]
[Authorize(Roles = "prototype-user")]
public IActionResult RegisterRecord([FromBody]IEnumerable<Record> records)
{
try
{
var result = Service.AddRecord(records);
if(result)
return Ok();
else return BadRequest();
}catch (Exception ex)
{
return BadRequest(ex);
}
}
}
Record.cs
public class Record
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string GUId { get; set; }
public int RecordState { get; set; } // have default db value
public DateTime Timestamp { get; set; }
public DateTime ModifiedTimestamp { get; set; } // have default db value
public long Id { get; set; } // auto increment
}
Here is my code snippet in React:
handleSubmit() {
var data = new Object();
data.firstName = this.state.firstName;
data.middleName = this.state.middleName;
data.lastName = this.state.lastName;
data.guid = "";
data.timestamp = this.formatDate(new Date().toLocaleString() + "");
var url = this.getBaseUrl() + "/record/addrecord";
fetch(url, {
method: "POST",
credentials: "include",
headers: {
'Authorization': `Bearer ${this.state.token}`, //this token is from keycloak.token
'Content-Type': 'application/json'
},
credentials: "same-origin",
body: JSON.stringify(data),
}
).then((response) => {
if (response.status == 200) {
return response.json()
} else {
throw new Error(response.statusText)
}
})
.then(result => {
console.log(result)
}).catch(error =>
alert(error)
)
}
render() {
return (
<div>
<label>
First Name: <input name='firstName' className='textbox' type="text" value={this.state.firstName} onChange={this.handleChange} />
</label>
<label>
Middle Name: <input name='middleName' className='textbox' type="text" value={this.state.middleName} onChange={this.handleChange} />
</label>
<label>
Last Name: <input name='lastName' className='textbox' type="text" value={this.state.lastName} onChange={this.handleChange} />
</label>
<input className='submit' type="submit" value="Add Record" onClick={() => this.handleSubmit()} />
</div>
}
}
This code will execute once I click the submit button. This results to 400 Bad Request issue. I already tried my API on postman and is working using Keycloak Autentication. I also tried GET methods on my other APIs and are also working using my React app. I do not know what is wrong with my POST method.
For reference, here is my GET method that is working perfectly:
getrecords(){
var url = this.getBaseUrl() + "/record/getrecord";
fetch(url, {
method: "get",
credentials: "include",
headers: {
'Authorization': `Bearer ${this.state.token}`,
},
}).then((response) => {
if (response.status == 200) {
return response.json()
} else {
throw new Error(response.status)
}
})
.then(result => {
this.setState({ recordlist: result })
}).catch(error =>
alert(error)
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
