1

GET http://localhost:3000/api/fetch?search=12312321 404 (Not Found) cors issue in Reactjs and node js i use the proxy method in Reactjs but can't get rid from it please help me

proxy

"proxy":"http://localhost:5000/"

tried both

"proxy":"http://localhost:5000"

express

RegisterRoute.route('/fetch/:id').get( ( req , res) => {

console.log("called by someone ",req.params.id);

res.send("okey will");

});

Reactjs function which will call the backend api

FetchNotification(){

    axios({

        'method':'GET',

        'url':'api/fetch',

        'headers': {

            'content-type':'application/octet-stream',

            'x-rapidapi-host':'example.com',

            'x-rapidapi-key': process.env.RAPIDAPI_KEY
         }
         ,
        'params': {

            'id':'12312321'
        },
    })


}

when i simply call axios.get it perfectly work but when i give params to it it gives the error xhr:178 404 not found

a simple server which also returns the same result

const express = require('express');

const cors= require('cors');

const app= express();

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json

app.use(bodyParser.json());

app.use('*',cors());

app.get('/fetch/:id',(req , res) => {

console.log("calling",req.params.id);

}); app.listen(5000);

lynn chris
  • 21
  • 5
  • Are you still getting the CORS error in the browser console or just the 404 response from the API in the network tab in Dev Tools in browser? Also, it would help if you can share the code where you are making the api request from UI as well as the part where the API is exposed at the backend. – Ankush Raghuvanshi Jun 05 '20 at 22:22
  • i think this is not about cors because other api's such as post and get witout params are working perfectly for checking cors i also set the proxy in pkg,json and run the server and client concurrently and i find that the error comes when i give params to get i'm sharing the both api please chech now i have a pain in my head – lynn chris Jun 05 '20 at 22:49
  • Backend) RegisterRoute.route('/fetch/:id').get((req,res)=>{ console.log("called by someone ",req.params.id); res.send("okey will"); }); – lynn chris Jun 05 '20 at 22:51
  • React FetchNotification(){ axios({ 'method':'GET', 'url':'api/fetch', 'headers': { 'content-type':'application/octet-stream', 'x-rapidapi-host':'example.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY } , 'params': { 'id':'12312321' }, }) } – lynn chris Jun 05 '20 at 22:55
  • Firstly, would be great if you could move the code info in the comments to the questions (you can read stackoverflow's FAQs about "how to ask a question"). Also, would be great if you could add the package.json code as well. – Ankush Raghuvanshi Jun 05 '20 at 22:58
  • Further, if you don't see a CORS error in the "Console" tab of Dev Tools of the browser and only the 404, then it means you've probably misconfigured the naming or port of the API. – Ankush Raghuvanshi Jun 05 '20 at 22:59
  • i share the code above check if their is any error but other apis are working perfectly even get is working without params – lynn chris Jun 05 '20 at 23:03
  • As per the code you've shared,you are using http://localhost:5000 as proxy. So should i assume your Express server is listening to calls on port 5000? Also, see this as to how you should handle the api calls in Express -> https://expressjs.com/en/starter/hello-world.html Unless you are trying achieve something by using "RegisterRoute.route" – Ankush Raghuvanshi Jun 05 '20 at 23:29
  • yes 5000 is my backend port okey but register route is just a express router.route and then i define apis other's are also written in the same way so what is the problem should i use to define apis again? i also make a server couple of minutes ago their i simply call app.get then it also return the same error what should i do now – lynn chris Jun 05 '20 at 23:36
  • it is a very odd behaviour i tried both by express router and from simple server instance.api but nothing works and why it just show error on params its completely freeze my mind – lynn chris Jun 05 '20 at 23:41
  • Can you add to your question the whole app.js or index.js of the express server where you are creating or i should say initiating your express server? That would help debug it better. Most probably, you'll have to either update the api at the express from /fetch to /api/fetch or vice versa on the UI, unless you are specifically handling /api requests in a separate module on express, which can only be cleared if you share your app.js or index.js code. – Ankush Raghuvanshi Jun 05 '20 at 23:41
  • look i have posted the server code which also returns the same error – lynn chris Jun 05 '20 at 23:52

3 Answers3

2

I can see that you're using Nodejs as server side. So, you can try changing following line

app.use('*',cors());

to

app.use(cors());

If this doesn't solve the issue, you can try adding a google chrome extension for CORS (Most probably). In this way, you'll not need any proxies being set for running servers.

Also, you need to do a small change in URL, instead of calling

'url':'api/fetch'

you need to provide an id in your call, because the backend api is accepting a parameter

'url':'api/fetch/some_id'
0

I feel there are multiple issues. I'll try to address them one by one.

Firstly, if you are proxying your requests correctly (which I think you are as per your package.json), then you'd not require the cors package. So you can get rid of that package.

Read more about why you shouldn't let all incoming request bypass the CORS check from security point of view -> Is it safe to enable CORS to * for a public and readonly webservice?

Now secondly, the url which you've specified on the frontend is 'url':'api/fetch', which means browser will make a call to http://localhost:3000/api/fetch?search=12312321 which it correctly did as seen in your error statement for 404.

Specifying the proxy as "proxy":"http://localhost:5000" in package.json means that now you are making requests to http://localhost:5000 instead of http://localhost:3000, but the browser would still think its http://localhost:3000. That's the whole purpose of proxying and how you kinda fool browser to do CORS without throwing any error.

But because on your server, you are listening to app.get('/fetch/:id',(req , res) instead of app.get('api/fetch/:id',(req , res), it doesn't matches with this URL as you have not explicitly handled requests starting with /api in some separate router module either.

So you should either update the url in the axios call to url':'/fetch while the proxy value in package.json is "proxy":"http://localhost:5000" or url':'fetch and "proxy":"http://localhost:5000/" respectively. Notice how i've used the /

OR

You can update the URL on the express end to app.get('api/fetch/:id',(req , res)

Lastly, whenever you receive a request, you need to return some value(string or JSON or even status code) as result. In your case, you've simply console.log("calling",req.params.id); and didn't send back any response to the UI.

So even if your 404 would resolve after fixing the URL, you'd bump into request timeout error (408) as your UI will keep waiting for a response from the server while you didn't send any.

So you should do something like this maybe:

app.get('api/fetch/:id',(req , res) => {
    console.log("calling",req.params.id);
    res.send("It worked");
});

Notice how there's a response being sent back -> https://expressjs.com/en/starter/hello-world.html If you don't want to send back a response, then you can simply return status like 200, 504 etc.

Ankush Raghuvanshi
  • 1,392
  • 11
  • 17
  • hey thanks for your reply i really appreciate your work i remove the cors but i dont think that proxying the url call is generating this error because you can call get without params it only show error when i send param so proxy just hides the backend port with frontend port to get rid of cors so we can use both techniques either i use cors in backend without proxy method or i use proxy without cors in front backend and there is not problem with my react router i debug the routes properly it just show error when i give params and i have tried that things you mention still can't understand – lynn chris Jun 06 '20 at 19:26
  • and i also remove the expressrouter.route().get but still it is not sending params – lynn chris Jun 06 '20 at 19:29
  • i was trying caling api using api/fetch?id=value and i can only access it via req.query but i was doing req.params so for params it was not the way for params i should cal from frontend api/fetch/id=value this was the problem really appreacitive for me you was trying to help me it means alot thanks buddy – lynn chris Jun 06 '20 at 19:45
  • Usually if you are making a GET call, then you shouldn't really need to send a JSON obj from frontend to backend as body. GET calls are primary meant to get some data based on ID or username etc. Basically a single value. Hence the convention is to use ` api/fetch?id=value` and extract it from query params at the backend. If you are sending complex JSON as the value, then you'd need to encode that URL as well, though you should consider correcting the design in the first place. – Ankush Raghuvanshi Jun 08 '20 at 03:08
  • So you can use POST requests to send complex JSON, though according to the convention POST should ideally be used when you want to save / update something. And yes, you are right that we can use both solutions to get rid of CORS issue, but read why using the CORS package is harmful as compared to proxying method because you were simply allowing all request to make CORS, which is a big NO from security point of view. And happy to help mate. – Ankush Raghuvanshi Jun 08 '20 at 03:11
  • yes you are right i think by doing proxy the required url is a good approach on the other hand when we use cors package then it allow all the urls to call api and that approach is insecure and i will read about it that you prescribe me :) – lynn chris Jun 08 '20 at 19:27
-1

if you apply below code in backend/server i thing it will debug.

  app.get('api/fetch/:id',(req , res) => {
    console.log("calling",req.params.id);
    res.send("It worked");
});
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 11 '22 at 16:05