Encountering CORS Error while trying to access Guest App in Virtualbox using Vue, Express, and Axios

I encountered an issue while trying to access my Vue app in Virtualbox from the host, both running on Linux Mint 20. Although I can now reach the login page from my host, I am consistently faced with a CORS error during login attempts:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/login. (Reason: CORS request did not succeed)

Host Headers:

{
    "OPTIONS": {
        "scheme": "http",
        "host": "localhost:3000",
        "filename": "/login"
    }
} 
{
"Transferred": "0 B (0 B size)",
"Referrer Policy": "no-referrer-when-downgrade"
}

OPTIONS /login undefined
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:8080/login
Origin: http://localhost:8080
DNT: 1
Connection: keep-alive

Guest Headers:

{
    "OPTIONS": {
        "scheme": "http",
        "host": "localhost:3000",
        "filename": "/login",
        "remote": {
            "Address": "127.0.0.1:3000"
        }
    }
}
{
    "Status": "204No Content",
    "Version": "HTTP/1.1",
    "Transferred": "374 B (0 B size)",
    "Referrer Policy": "strict-origin-when-cross-origin"
}


HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:8080
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type
Content-Length: 0
Date: Thu, 08 Apr 2021 19:48:16 GMT
Connection: keep-alive

OPTIONS /login HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:8080/
Origin: http://localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

I have configured a NAT and set up port forwarding for both host and guest using port 8080, although I also attempted using a Bridged Adaptor.

package.json:

"dev": "webpack-dev-server --host 0.0.0.0 --progress --config build/webpack.dev.conf.js",

Server Code:

app.use(cors({ origin: 'http://localhost:8080' , credentials: true }));
app.options('*', cors());

router.post('/login', (req, res) => {
    db.selectByEmail(req.body.email).then((response) => {
        ...
    }).catch((response) => {
        ...
    });
});

let port = process.env.PORT || 3000;

let server = app.listen(port, function() {
    console.log('Express server listening on port ' + port)
});

Request from Vue:

this.$http.post('http://localhost:3000/login', {
    email: this.email,
    password: this.password,
})
.then(response => {
    ...
})
.catch(function (error) {
    ...
});

Answer №1

After some troubleshooting, I was able to successfully resolve the issue. By adjusting the VM network configuration to Bridged Adaptor and updating the server call from Vue to use the VM's IP address instead of 'localhost', everything started working smoothly.

this.$http.post('http://192.168.1.x:3000/login', {
    email: this.email,
    password: this.password,
})

Answer №2

Did you consider enabling all headers?

app.use(cors());

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

Merge the outcomes of two queries into a unified array using the power of expressjs, mysql, and nodejs

Can anyone guide me on how to structure a result in the following format: [ { "id_user":1, "name":"foo", "last_name":"bar", "id_rol":{ "id_rol":1, "rol_name":"admin" } }, { "id_user":2, "name":"foo2", "las ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

Authentication middleware is triggered when a request is made to routes that are not valid

In my application, I have both public and private routes. // public router.use(publicRoute); // After this all Routes are private router.use(runAsyncWrapper(isAuthenticated)); // private router.use(privateRoute); Additionally, there is a catch-all route ...

The installation of AngularJS libraries via npm was unsuccessful

After installing mean.io and running sudo npm install, I followed the commands in sequence: sudo npm install -g meanio mean init yourNewApp cd yourNewApp sudo npm install -g bower sudo npm install The process was supposed to download and install AngularJ ...

Invalid file format for product images in Magento version 1.9.0.1

Every time I try to upload an image in the product option, Magento 1.9.0.1 gives me an error saying "Disallowed file format." ...

"Performing Mongodb queries on elements located at any position within an

This is the structure of my schema: { _id: "myid" user: [{"name":"Bob"}, {"name":"Jenny"}] }, { _id: "myid2" user: [{"name":"John"}, {"name":"Jenny"}] }, { _id: "myid3" user: [{"name":"John"}, {"name":"Bob"}] } I am trying to locate all the d ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

Let the Vuejs transition occur exclusively during the opening of a slide

Trying to implement a smooth transition when the toggle button is clicked. Successfully applied the transition effect on the slider, but struggling to animate the text inside the div.hello class upon sliding open. <transition name="slide"> <a ...

Keeping track of both the search query and the results

I have stored the current search term in a state using e.target.value as searchField, but when I clear the input value, I can no longer use it. I want to display a message in the body informing the user that their specific searched term yielded no results, ...

Error: The index $_GET[...] is not defined

When transferring a javascript variable to a php file, I encounter an issue where $_GET['something'] keeps returning as an undefined index. Despite this error, the correct result is displayed and written into the xml. However, when I attempt to ...

Determining the optimal scenarios for utilizing debug compared to alternative logging frameworks

NodeJS offers two well-known logging frameworks: winston and Bunyan. Additionally, there is a tool called debug. From my understanding, all of these tools essentially serve the same purpose - which is to log information. debug comes as a default component ...

Intersecting realms document

Currently I am working on a web store using Magento Go. Unfortunately, this platform does not support server side scripting languages such as PHP. Despite this limitation, I still need to save order data post successful checkout and share it with my shippi ...

ExpressJS does not support the 'Save' function

Working on a ticketing API using NodeJS + ExpressJS. Encountering an error when trying to modify a previously created ticket using the PUT method. Error /home/ismael/projects/nodejs-ticketing/routes/ticket.js:38 item.save(function(err){ ...

Begin by sorting and limiting Mongoose's results based on one attribute, followed by sorting by another attribute

Is there a way to retrieve the top n datasets with the highest count, but have them sorted by name? I attempted the code below, however it did not yield the desired results. db.Foo .find() .sort({'count': -1}) .limit(n) ...

Setting up a web server with a cyclical challenge

I've encountered an issue while hosting my server.js file with the configured API on Cyclic. The deployment was successful, but every endpoint call is returning a status 500 error. Additionally, I have hosted the React front-end on github pages. I&apo ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

Verify the definition of the checkbox

I'm attempting to determine whether a checkbox is defined and unchecked. When the page loads, my checkbox is disabled and I receive an error indicating that it is undefined. I attempted to create a condition to prevent the error but was unsuccessful. ...

Utilizing Google Analytics with Laravel Jetstream

Currently, I'm facing challenges with setting up Google Analytics to properly report data with the InertiaJS stack on Laravel Jetstream. My goal is to track individual page visits within this single-page application, but I'm uncertain about the a ...

The ajax POST method fails to trigger in a Node.js environment

Having an issue with the POST request. It's necessary for updating info without page reload. Below is my pug code: .tinder--buttons form(id="form1") button#love(type="submit") i.fa.fa ...