Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the

this.http.post('http://localhost:8000/login', body, { headers: contentHeaders })
API, Chrome shows the following response:

XMLHttpRequest cannot load http://localhost:8000/login. The request was redirected to 'http://localhost:8000/', which is disallowed for cross-origin requests that require preflight.

However, when calling the

this.http.post('http://localhost:8000/register', body, { headers: contentHeaders })
, everything runs smoothly and handles all the registration processes (such as password hashing and data storage in the database).

Below is a simplified version of the register API from (register.js):

 router.post('/', function (req, res) {

    if (req.body.email && req.body.password) {
        var User = require('../../models/user');

        User.create({
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
        }).then(
            function() {
                res.render('user/registered', {registered: true});
            },
            function() {
                res.render('user/registered', {registered: false});
            }
        );
    } else {
        res.render('user/registered', {registered: false});
    }
});

And here is the Login API from (login.js):

 router.post('/', function (req, res) {

    passport.authenticate('local', {
        successRedirect: req.session.goingTo || '/',
        failureRedirect: '/login',
        failureFlash: true
    })(req, res);

});

Answer №1

To activate CORS in your primary server script, include the following code:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the reference value from a dropdown box and pass it to another component?

Currently, I am in the process of creating a chat application using socket.io. Within this application, there is a dashboard component that consists of two child components known as Room.js and Chat.js. The Room component serves the purpose of selecting th ...

The image slide change feature ceases to function properly when incorporating two separate functions

I have a function that successfully changes the image of a container every 5 seconds. However, I am facing an issue when trying to add 2 containers side by side and change their images simultaneously. When I run the functions for both containers, only one ...

Using ng-transclude directive allows for encapsulating HTML content within an ng-transclude element

My directive includes an ng-repeat in the template and also has an ng-transclude option after the repeater to allow users to input their own content. The issue arises when the custom content is surrounded by an ng-transclude element upon rendering, which i ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

One way to enhance user experience is by passing parameters dynamically from the database when an element is clicked. This allows for the retrieval of

Earlier, I tried to post a question but couldn't get it working due to incorrect code. As the title suggests, my objective is to retrieve data from a database and display it in a div. The idea is that when this data is clicked, it should be passed to ...

The function jquery__WEBPACK_IMPORTED_MODULE_4__.hubConnection is not recognized

I am currently trying to integrate singlar (not ASP.Core) with angular 8. If I directly include signalr and jQuery in index.html as follows: <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWS ...

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

Assistance for Angular 2 Style Guide within Atom: Feature Needed!

My manager uses Atom with a set of eight plugins specifically designed for Angular development. I have the same plugins installed on my system, but I seem to be missing a feature that he has. We're unsure which plugin or preference setting is required ...

Generate a responsive list with a pop-up feature under each item (using Vue.js)

Currently, I believe that Vue may not be necessary since most tasks can be done using JavaScript and CSS. I am attempting to design a list layout as follows: [A] [B] [C] [D] When an item is clicked, the information about that specific item should ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

Communication between Angular Controller and Nodejs Server for Data Exchange

Expanding on the solution provided in this thread, my goal is to implement a way to retrieve a response from the node server. Angular Controller $scope.loginUser = function() { $scope.statusMsg = 'Sending data to server...'; $http({ ...

Displaying code within an Angular 2 template

Working on an Angular 2 project and facing a challenge in displaying C# code within the template, which may later be styled with syntax highlighter. The issue arises when attempting to insert the C# code into the Angular 2 template, resulting in template ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...

How can the input validation be displayed in Ajax when the user interacts with it?

When utilizing Ajax, I only want to display validation for the input field that the user is interacting with, not all validations at once. Currently, my script shows all validations simultaneously when any input is filled out. How can I modify my code so t ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...