Search code examples
node.jsangularauthenticationcorshttp-authentication

Angular 8 / NodeJS CORS error: Redirect location disallowed


I am using Angular 8 with a NodeJS backend in a lab environment. I have a button in Angular which sends a value to the backend server using a POST request. When the value is received, the backend reaches out to an API server based on the value from the form which returns a status code in JSON which I need to use for conditionals in the frontend.

The Angular button logic looks like this:

      this.form = this.fb.group({
        ticket: [''],
      })
    }

const testTicket = this.form.value.ticket

submitForm() {

   this.http.post('http://backend.com:8090/api/backendquery?testTicket='+ testTicket ,{}).subscribe (
            (response) => {
              console.log(response)
              if(response != 'failure') {
              this.ticketFound=true
              this.ticketNotFound=false
              status = 'Success'
              } else {
              // if(response == null) {
              this.ticketNotFound=true
              this.ticketFound=false
              status = 'Failed'
              }
    })
  }

The backend code reaching out to the API server looks like this:

var cors = require('cors'); 
app.use(cors());

app.post('/api/backendquery', function(req, res){
res.redirect('https://username:password@myserver.com/ticketquery='+req.query.testTicket); 
 });

I passed the credentials in the URL since the API server requires authentication.

I obtain the results successfully from Postman using the following URL:

http://backend.com:8090/api/backendquery?testTicket=12345

However, when using the browser by submitting the value, I get the following error on console:

'http://backend.com:8090/api/backendquery?testTicket=12345' from origin 'http://frontend:4200' has been blocked by CORS policy: Redirect location '' contains a username and password, which is disallowed for cross-origin requests.

As you can see in the backend code, the CORS package is already enabled which should take care of CORS errors. I aware that credentials should not be present in URLs, however, what could be take best approach in my situation?


Solution

  • The answer was that instead of redirecting in the backend, the GET request was done using the "required" package and then saved to a variable which was then forwarded back to the frontend.