1

I am using axios in reactjs which is running on port 3000 & Rails 6 API application is running in 3001.

I hit for /authenticate POST API & checked in the browser network tab for xhr tab where I found status as (cancelled) and no response or error.

On rails log,

Started POST "/api/v1/authenticate" for ::1 at 2020-09-04 09:56:49 +0530
Processing by Api::V1::AuthenticationController#authenticate as HTML
  Parameters: {"email"=>"[email protected]", "password"=>"[FILTERED]", "authentication"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}

Please suggest what I am doing wrong here

My axios call is like below,

  const response = await axios({
    URL: "http://localhost:3001/api/v1/authenticate",
    method: "POST",
    data: {"email":"[email protected]","password":"123123123"},
    headers: { 'Content-Type': 'application/json' }
  });

I followed reference but did not work

src/setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
  app.use(
    '/api/v1',
    createProxyMiddleware({
      target: 'http://localhost:3001/',
      changeOrigin: true,
    })
  );
};

API seems right as following return token in response json data,

curl -H "Content-Type: application/json" -X POST -d '{"email":"[email protected]","password":"123123123"}' http://localhost:3001/api/v1/authenticate

1 Answer 1

1

I'm not sure if you're using Devise or not, but I use Knock for JWT, which has a nasty habit of requiring a data to include auth like this:

const response = await axios({
    URL: "http://localhost:3001/api/v1/authenticate",
    method: "POST",
    data: {"auth": {"email":"[email protected]","password":"123123123"}},
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }
  });

while Devise requires additional header Accept: application/json

Refer here -> https://github.com/nsarno/knock#authenticating-from-a-web-or-mobile-application

https://github.com/heartcombo/devise/wiki/API-Mode-Compatibility-Guide

Don't know if this answers your question though.

Sign up to request clarification or add additional context in comments.

2 Comments

I am going to delete a question as it was a silly mistake from the front end. Axios call was getting canceled due to a button element on which it got called with onClick event, had type="submit" which eventually trigger form submit. So I had to change the type.
If you do not provide Accept inside header, it assumes it is HTML type and for this request API can render JSON data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.