1

Basically, I'm trying to get a username by id from Sequelize. The problem is that I am either stuck with a CORS problem or 500 Internal Server error depending on the response(status)

cors and 500

controller code

    async getUserFromUserId (req, res) {
        try {
            // const user = await User.findByPk(req.body.id)
            const id = req.body.id
            const user = await User.findByPk(id)
            res.send(user.username)
            } catch (err) {

            // or res.status(some random number).send() for CORS problem to appear

            res.status(500).send({
                error: 'an error has occured trying to fetch the users id'
            })
        }
    },

client code

this.notifiedUser = (await UserService.getUserFromUserId({id: UserId})).data

I get a Status: 200 OK from postman though. Postman Solution

Edit: I have seen how the other Solution for the cors thingy, but the solutions does not specify as to why I get "undefined" results after resolving the cors problem.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
tokibitsu
  • 19
  • 1
  • 1
  • 5
  • 1
    Postman is not cors restricted like browsers are. Implement cors middleware server side – charlietfl Mar 31 '19 at 22:09
  • wow the simplicity of ur explanation actually helps a ton, rather than looking at all the other related cors problem that is explained in a multitude of words. thanks. – tokibitsu Mar 31 '19 at 22:11
  • Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – JJJ Apr 01 '19 at 11:11

3 Answers3

4

So, CORS is actually really obnoxious in this regard, but there's a fairly straightforward way to fix this. It's a super useful security feature, though it is frustrating at best sometimes.

Your browser does what is called a Preflight Request, which is of the http verb OPTIONS. Your browser calls whatever route you want, but instead of what you asked it to do, it calls using OPTIONS first. Your server should accept all routes that the client can ask for with the OPTIONS method, and your server should respond with the following headers to be an externally available, cross-origin API.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, ...

(note, you should not put the ... in, but you can put any HTTP verb in this list)

If you require your own headers (for auth purposes), you want to add this header for Client -> Server.

Access-Control-Allow-Headers: YourHeader, YourHeader2, YourHeader3

You want to add this one for Server -> Client

Access-Control-Expose-Headers: YourHeader,YourHeader3

Note that the OPTIONS call is an entirely separate call that you should handle as well as the GET method.

You've now told the browser what it is allowed to ask for, and what it can expect to get back from your API. If you don't respond to the OPTIONS request, the browser terminates the request, resulting in a CORS error.

I'm going to take a gander at a guess and assume you're likely using Express, which this answer describes how to set the headers on.

What do the headers mean, in English?

Access-Control-Allow-Origin From where are clients allowed to access this resource (endpoint)? This can match partial domains with wildcards, or just a * to allow anywhere.

Access-Control-Allow-Methods What HTTP methods are permissible on this route?

Access-Control-Expose-Headers When I get a response from the server, what should I (the browser) expose to the client-side?

Access-Control-Allow-Headers What am I as the client side allowed to send as headers?

Rachael Dawn
  • 819
  • 6
  • 13
  • correct, I am using express. so instead I just did this: var cors = require('cors') app.use(cors()). So I believe this handles creating middleware for handling CORS through Express. The problem though now is, I am getting "undefined" as a result of my res.send(user.username). – tokibitsu Mar 31 '19 at 23:03
  • 1
    Splendid! That means you're halfway there. At the link at the end of this comment, scroll down and find the section that says `Enabling CORS Pre-Flight`, and examine how it responds to the `options` request. https://expressjs.com/en/resources/middleware/cors.html – Rachael Dawn Mar 31 '19 at 23:06
  • @charlietfl That's true, it should. If it were doing so, he wouldn't be running into CORS errors though, as they'd have been resolved by the middleware. I find CORS is one of those technologies that are super important to understand, and there aren't many good explanations of what is going on behind the scenes with CORS. – Rachael Dawn Mar 31 '19 at 23:13
  • 1
    hey thanks a lot man for helping out! i'll later try to do what you're asking and I'll see how it goes – tokibitsu Mar 31 '19 at 23:25
0

Okay, so I figured out the problem. In a way, I did not have to deal with any of the cors stuff because I believe that was not the main source of the problem.

So, instead of accessing my database data through "GET" and getting the data by doing this:

this.data = (Service.function(bodyValue)).data 

I did "POST" to get the data, and accessed the data by simply doing this

const response = Service.function({
                    id: bodyValue
                })
this.data = response.data

This accesses the data without having to get "secured" information from the database, but by accessing the data from the database by getting Observer object info from the database.

The Observer object looks as follows, which treats the user data as an object instead of pure data.

Compared to a data object, where each data {...} has user information.

I am not sure if I am using the correct words, but these are to the extent of my current understanding.

tokibitsu
  • 19
  • 1
  • 1
  • 5
-2

If your origin is from localhost, Chrome usually blocks any CORS request originating from this origin.

You can install this extension:

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

Or you can disable the security when running chrome (add the flag):

--disable-web-security

XDProgrammer
  • 853
  • 2
  • 14
  • 31
  • 3
    I use cors in localhost all the time with no issues – charlietfl Mar 31 '19 at 22:29
  • I have done this, now the result is "undefined". is there a way to fix this?, what is the problem occuring now? thanks for the feedback! – tokibitsu Mar 31 '19 at 22:29
  • 1
    Localhost isn't in any way special when it comes to CORS. The request is cross-origin if the domain, protocol or port doesn't match, and that's it. – JJJ Apr 01 '19 at 11:10