gothinkster/koa-knex-realworld-example

POST /api/articles works fine on Postman but giving Unauthorized error while requesting from superagent

blackdeve opened this issue · 12 comments

Here's my code:

import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';

const superagent = superagentPromise(_superagent, global.Promise);
const API_ROOT = 'http://localhost:3000/api';

const Articles = {
    create: article =>
    superagent.post(`${API_ROOT}/articles`, { article })
      .set('Content-Type', 'application/json')
      .set('Authorization', `Token ${token}`)
      .set('X-Requested-With', 'XMLHttpRequest')
      .then(res => res.body)
}

This is error log of the Articles.create() function.
issue

Is there anyone who can fix this issue for me?
Thanks in advance!

X-Requested-With header is not allowed in CORS settings here: https://github.com/gothinkster/koa-knex-realworld-example/blob/master/src/config/index.js#L31

it works in postman, bcs. browser has CORS mechanism for better security https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

why do you actually need this http header X-Requested-With?

If I remove X-Requested-With header, it gives Unauthorized error.

issue

Do you have any idea about this?
It works fine on Postman with the same Authorization header.

Looks like you use wrong token or bug in the application logic
needs more info

  1. is it only on POST /api/articles endpoint or others too?
  2. do you use the same host and token in postman and in the browser?
  3. how do you get the token?

in your create function, I don't see token at all

  1. Others also get errors
  2. Yes, I used same token in postman and in the browser
  3. I get token by POST /api/users/login

token is stored globally and it's updated when user logs in

can you also check in Chrome network tab that your actual XHR request contains the right header and the right value

yes, it has right header and values

xhr

works fine for me in chrome console
screen shot 2018-08-30 at 21 28 14

make sure, that you receive and send the token to the same host

if doesn't work, create small reproducible example/repo to see what the problem, please

I tried with your code but it gives me error as well

Code :
screen shot 2018-08-31 at 12 45 51 pm

Error:
screen shot 2018-08-31 at 12 47 11 pm

Does this mean there is bug on my backend?

perhaps, this needs debugging to get the wrong place

what do you mean exactly?

I mean it's not clear where is the problem.
It could be both sides and needs debugging with some reproducible examples

closed due to inactivity