I attempted to implement "cors" in my project, but encountered the error message "Access to XMLHttpRequest has been blocked". What could be causing this issue?

I am facing an issue with my express API where I receive a CORS error message after making a request.

Error:
Access to XMLHttpRequest at 'http://localhost:9000/api/courses' from origin
'http://localhost:4222' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

In my API, I have implemented cors and below is the relevant code snippet:

import * as express from 'express';
import {Application} from "express";
import {getAllCourses, getCourseById} from "./get-courses.route";
import {searchLessons} from "./search-lessons.route";
import {loginUser} from "./auth.route";
import {saveCourse} from "./save-course.route";

const bodyParser = require('body-parser');
const app: Application = express();

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

app.route('/api/login').post(loginUser);
app.route('/api/courses').get(getAllCourses);
app.route('/api/courses/:id').put(saveCourse);
app.route('/api/courses/:id').get(getCourseById);
app.route('/api/lessons').get(searchLessons);

const httpServer = app.listen(9000, () => {
    console.log("HTTP REST API Server running at http://localhost:" + httpServer.address().port);
});

Your assistance in resolving this matter would be highly appreciated. Thank you in advance for your responses.

Answer №1

Provide a source for this

app.use(cors({
  origin: 'http://myappsite.com'
}));

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

The compilation of usernames of clients currently connected through socket io

After creating a chat client with various chat rooms using NodeJS, socketIO and Express, I am looking to show an updated list of all connected users in each room. Is there a way to link a username to an object so that I can easily access it like this: var ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

Setting a cap on file sizes in Azure websites

I am currently attempting to upload a file from the front-end to the back-end and save the file on Azure Storage. My code functions properly when the file size is below 30mb, however, it fails if the file size exceeds 30mb. console.log('- 11111 -&apo ...

What is causing this problem with my terminal when I attempt to install Sass?

I am having trouble with the installation of Sass using Terminal. When I try to run npm install -g sass, I am encountering an error in the log file. The response I get is as follows: npm WARN checkPermissions Missing write access to /Users/dagilo/desktop/n ...

Pattern for identifying JavaScript import declarations

My task involves using node to read the contents of a file. Specifically, I am looking to identify and extract a particular import statement within the file that includes the "foo-bar" package. The goal is to match only the line or lines that contain the ...

Node.js not receiving expected Ajax response

Why is my Ajax request not receiving the proper response? It always shows readyState '4' with a response status of '0'. What could be causing this issue? Client-Side Code: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = f ...

"Learn how to seamlessly submit a form without reloading the page and send data back to the same page using Node and Express

I've already reviewed a few questions on this platform. They all focus on submitting post requests, but I believe the process should be similar for get requests as well. Therefore, I made modifications to my code to accommodate get requests. However, ...

Can you help me identify the issue with my current Jade for loop implementation?

Here is my full loop code written in Jade: block content div(class='row') div(class='col-lg-12') h1(class='subject') 로또라이 div(class='row') div(class='col-lg-8') - for (var ...

Utilizing Handlebars with Passport.js to capture user input

Currently diving into the world of node.js with passport, handlebars and mysql as my tools of choice. The goal is to design a signup page that collects email address, password, first name, and last name. However, when using passport, it only accommodates ...

Deploying NodeJS applications using PM2, with support for both clustered and single instances

Consider the following scenario: The server has a scoped pm2 instance running in the /project directory A new version of the app is pushed to master branch The continuous integration (CI) system builds the new version How can I instruct CI to deploy the ...

Exploring JADE within the NodeJS Technology Framework

Currently, I am developing a proof of concept in Node JS, and from my research, the standard tech stack typically consists of Jade (as opposed to HTML), NodeJS, and a database. My query is whether we can substitute HTML 5 for Jade instead. This way, I can ...

next.js encountered an issue: Error: > Compilation unsuccessful due to webpack errors

I encountered some errors while trying to deploy my nextJs app and running npm run build. Here are the details of the error: Error during the build process: Error: The build failed due to webpack errors at /Users/hassan/Upwork/ROCProjectNext.js/ROCNext/no ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Creating a dynamic Google Chart by fetching data from MongoDB with AJAX/JQuery

After completing the MongoDB tutorial for nodejs on their website, I am in the process of creating a simple test case to send query results to a Google Chart using AJAX. Below is the nodejs code snippet used to form the query: CODE: var MongoClient = re ...

Guide on updating a specific item in a JSON array using npm request

I am currently working on setting a value in a JSON array utilizing a PUT request with the request module, specifically targeting one of multiple main objects within the array. The structure is as follows: [ 0: { status: 'pending' ...

Error Detection: Unable to modify headers after they have been sent to the user in my PassportJS application

I encountered this error while working on my code. I'm not just looking for the location of the error, but also seeking a better method to log errors so that I can identify where they are occurring in my code. Even after checking the error log, I am u ...

Issue with Firebase not updating to Node version 12

I have followed the instructions provided at this link: https://firebase.google.com/docs/functions/manage-functions#upgrade-node10 As per the guidelines, I updated my package.json to specify Node 12 as the engine: "engines": { "node&quo ...

How can the Domain attribute of the Express.js cookie setter be utilized to share a cookie across multiple domains effectively?

Consider a scenario where you have the cookie setter code as follows: res.cookie('name', 'tobi', { secure: true, httpOnly: false, sameSite: 'None', domain: '.example1.com' }); To make the cookie ac ...

a function that is not returning a boolean value, but rather returning

There seems to be a simple thing I'm missing here, but for the life of me, I can't figure out why the function below is returning undefined. var isOrphanEan = function isOrphanEan (ean) { Products.findOne({ 'ean': ean }, func ...

Can templates be nested within other templates using different contexts?

I am in the process of developing an application using nodejs and handlebars. My goal is to create a layout template and insert various individual components into that layout. Each component will have its own handlebars template and context. e.g. layout. ...