Reputation: 91
I am trying to call an api and I get the error "Unhandled promise rejection: Error: Request failed with status code 500". I dunno how did I get the error.I put the api call in componentDidMount. I am not sure whether the error comes from the redux implementation or from how I called the api.
This is how I called the api. After a successful login, I put the username as a token and use it to call another api.
state={
username: '',
semcode: [
{}
]
}
componentWillMount() {
AsyncStorage.getItem('Login_token').then((token) => {
console.log('this is coursescreen',token);
let Login_token = token;
this.setState({ username: Login_token });
});
}
componentDidMount(){
this.props.getSemcode(this.state.username);
}
componentWillReceiveProps(nextProps) {
console.log('xx',nextProps);
if (nextProps.semCode != undefined) {
this.setState({ semcode: nextProps.semCode });
}
}
This is how I wrote my action file:
export const getSemcode = (username) => async dispatch => {
let param = {
nomatrik: username,
}
console.log(`${helper.ROOT_URL}/result/GetListOfKodSesiSem`)
let code_res = await
axios.post(`${helper.ROOT_URL}/result/GetListOfKodSesiSem`, param)
console.log(code_res.data);
if (code_res.data.length > 0) {
const { code } = code_res.data;
dispatch({ type: SEMCODE_FETCH_SUCCESS, payload: { semCode: code }});
}
}
This is how I wrote my reducer:
import { SEMCODE_FETCH_SUCCESS} from '../actions/types';
const INITIAL_STATE={
semCode:[],
}
export default function (state=INITIAL_STATE, action){
switch(action.type){
case SEMCODE_FETCH_SUCCESS:
return action.payload
default:
return state;
}
}
Can anyone help me pleaseeeeee
Error Message
Error received from axios.post: {"config":{"transformRequest": {},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF- TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers": {"Accept":"application/json, text/plain, /","Content- Type":"application/json;charset=utf-8"}, "method":"post","nomatrik":"BB16160907", "url":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem","data":" {\"Accept\":\"application/json\",\"Content- Type\":\"application/json\"}"},"request": {"UNSENT":0,"OPENED":1,"HEADERS_RECEIVED":2,"LOADING":3,"DONE":4, "readyState":4,"status":500,"timeout":0,"withCredentials":true,"upload": {},"_aborted":false,"_hasError":false,"_method":"POST","_response":" {\"Message\":\"An error has occurred.\"}", "_url":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem", "_timedOut":false,"_trackingName":"unknown", "_incrementalEvents":false,"responseHeaders":{"Date":"Sat, 30 Dec 2017 03:58:25 GMT","Content-Length":"36","X-Powered-By":"ARR/3.0","X-AspNet- Version":"4.0.30319","Expires":"-1","Content-Type":"application/json; charset=utf-8","Server":"Microsoft-IIS/10.0","Pragma":"no-cache","Cache- Control":"no-cache"},"_requestId":null,"_headers": {"accept":"application/json, text/plain, /","content- type":"application/json;charset=utf- 8"},"_responseType":"","_sent":true,"_lowerCaseResponseHeaders":{"date":"Sat, 30 Dec 2017 03:58:25 GMT","content-length":"36","x-powered-by":"ARR/3.0","x- aspnet-version":"4.0.30319","expires":"-1","content-type":"application/json; charset=utf-8","server":"Microsoft-IIS/10.0","pragma":"no-cache","cache- control":"no-cache"},"_subscriptions":[],"responseURL": "https://smp.ums.edu.my/api/result/GetListOfKodSesiSem"},"response":{"data": {"Message":"An error has occurred."},"status":500,"headers":{"date":"Sat, 30 Dec 2017 03:58:25 GMT","content-length":"36","x-powered-by":"ARR/3.0","x- aspnet-version":"4.0.30319","expires":"-1","content-type":"application/json; charset=utf-8","server":"Microsoft-IIS/10.0","pragma":"no-cache","cache- control":"no-cache"},"config":{"transformRequest":{},"transformResponse": {},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF- TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"},"method": "post","nomatrik":"BB16160907", "url":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem","data":" {\"Accept\":\"application/json\",\"Content- Type\":\"application/json\"}"},"request": {"UNSENT":0,"OPENED":1,"HEADERS_RECEIVED":2,"LOADING":3,"DONE":4, "readyState":4,"status":500,"timeout":0,"withCredentials":true,"upload": {},"_aborted":false,"_hasError":false,"_method":"POST","_response":" {\"Message\":\"An error has occurred.\"}", "_url":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem", "_timedOut":false,"_trackingName":"unknown","_incrementalEvents":false, "responseHeaders":{"Date":"Sat, 30 Dec 2017 03:58:25 GMT","Content- Length":"36","X-Powered-By":"ARR/3.0","X-AspNet- Version":"4.0.30319","Expires":"-1","Content-Type":"application/json; charset=utf-8","Server":"Microsoft-IIS/10.0","Pragma":"no-cache","Cache- Control":"no-cache"},"_requestId":null,"_headers": {"accept":"application/json, text/plain, /","content- type":"application/json;charset=utf- 8"},"_responseType":"","_sent":true,"_lowerCaseResponseHeaders":{"date":"Sat, 30 Dec 2017 03:58:25 GMT","content-length":"36","x-powered-by":"ARR/3.0","x- aspnet-version":"4.0.30319","expires":"-1","content-type":"application/json; charset=utf-8","server":"Microsoft-IIS/10.0","pragma":"no-cache","cache- control":"no-cache"},"_subscriptions": [],"responseURL":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem"}}}
Login action:
export const attemptLogin = (username, password) => async dispatch => {
let param = {
txtNomatrik: username,
txtPwd: password,
public_key: helper.PUBLIC_KEY,
secret_key: helper.SECRET_KEY
}
console.log(`${helper.ROOT_API_URL}/v1/basic/ad/std/login`)
let login_res = await
axios.post(`${helper.ROOT_API_URL}/v1/basic/ad/std/login`, param)
console.log(login_res.data);
await AsyncStorage.setItem('jwtToken',login_res.data.token);
if (login_res.data.status == 'Successful login') {
const { login } = login_res.data;
dispatch({ type: LOGIN_SUCCESS});
}
}
Upvotes: 0
Views: 32938
Reputation: 8035
You are looking in the wrong place.
An error code 500 is returned by the remote server when it can't handle the request. In this case, I suspect that the POST to ${helper.ROOT_URL}/result/GetListOfKodSesiSem
is failing. The axios library is a promise based library. Wrap the call in a try-catch block like this:
try {
console.log(`${helper.ROOT_URL}/result/GetListOfKodSesiSem`)
let code_res = await
axios.post(`${helper.ROOT_URL}/result/GetListOfKodSesiSem`, param)
console.log(code_res.data);
if (code_res.data.length > 0) {
const { code } = code_res.data;
dispatch({ type: SEMCODE_FETCH_SUCCESS, payload: { semCode: code }});
}
} catch (err) {
console.error(`Error received from axios.post: ${JSON.stringify(err)}`);
}
This will at least give you a view in your debug console on what is happening. You can then coordinate that call with any debug logs from the backend to figure out what the error really is.
Your root cause, however, is that the remote server is returning a Server Error (HTTP code 500) to your client.
Upvotes: 2
Reputation: 9885
Problem
Your request is failing because you are not adding the JWT token to the headers.
Solution
Using Axios and with your code this should work. Evidently our big problem here was that you have to pass data
even though it is empty. If we do not pass data
it fails with error 500
.
export const getSemcode = (username) => async dispatch => {
let jwtToken = await AsyncStorage.getItem('jwtToken').then((data) => {
console.log('this is semcode',data);
});
let config = {
method: 'POST',
url: 'url/to/sem',
headers: {
'content-type': 'application/x-www-form-urlencoded',
AntiTemperSignature: jwtToken,
UserID: '123456',
},
data: '',
json: true
};
try {
return axios(config)
.then((response) => {
console.log(response);
if (response.data.length > 0) {
const { code } = response.data;
dispatch({ type: SEMCODE_FETCH_SUCCESS, payload: { semCode: code } });
}
})
.catch((error) => {
console.log(error);
});
}
}
Upvotes: 3