Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have creates an api using php and i defined the

PHP
header("Access-Control-Allow-Origin: http://localhost:81/api/Students/read.php");
header("Access-Control-Allow-Headers: http://localhost:81/api/Students/read.php");


but when i used the express code it doesn't recognize it the code for my route
middleware that i made i express is below can any one help me

this is the route that i am using:

JavaScript
studentRoute.get('/Students/api' ,(req,res,next)=>{
    
    fetchs('http://localhost:82/students-Api/api/Students/read.php',{
        headers:{
            'Access-control-Allow-Origin':"http://localhost:81/api/Students/read.php"
        }
    })
    .then(response=>{
        response.json().then(data=>{
              console.log(req.xhr)
              res.send(data)
        }).catch(err=>{
            next(err)
        })
    }).catch(err=>{
        next(err)
    })
})


What I have tried:

i have tried to use the req.header to set header using this code :
JavaScript
<pre>
studentRoute.get('/Students/api' ,(req,res,next)=>{
    
    req.header("Access-control-Allow-Origin","http://localhost:81/api/Students/read.php")
    fetchs('http://localhost:82/students-Api/api/Students/read.php')
    .then(response=>{
        response.json().then(data=>{
              console.log(req.xhr)
              res.send(data)
        }).catch(err=>{
            next(err)
        })
    }).catch(err=>{
        next(err)
    })
})
Posted
Updated 9-Feb-22 22:26pm

1 solution

The CORS headers need to be sent in the response from the server you're trying to access, not in the request headers sent by your Javascript. If the initiating party was able to control the headers, then they wouldn't serve any purpose.

The Access-Control-Allow-Origin header should specify the origin, not the full URL. In this case, the origin would be http://localhost:81.

The Access-Control-Allow-Headers header is used to specify the name of the HTTP headers which can be sent. Specifying a URL for this header is invalid.

Cross-Origin Resource Sharing (CORS) - HTTP | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900