Issue encountered while attempting to connect to an Azure API, despite having the correct origin permissions set

Hey there! I currently have two web applications deployed on Azure - one serving as the frontend and the other as an API. The communication between the frontend and API is established using the following code:

@Injectable({
  providedIn: 'root'
})
export class UsuarioService {

  uri = 'https://myazureapi.azurewebsites.net';

  constructor(private http: HttpClient) { }

  login(usuario:string, senha:string){
    const Usuario ={
      usuario:usuario,
      senha:senha
    }
    return this.http.post<any>(`${this.uri}/login`, Usuario);
  }
}

In the API, I've set up the following structure where 'User' acts as a mongoose model:

const Express = require("express");
const mongoose = require("mongoose");
const BodyParser = require("body-parser");
const port=process.env.PORT||3000;
const jwt = require("jsonwebtoken");
var app = Express();

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", 
    "https://myazureapplication.azurerewebsites.net");
    res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    if (req.method === "OPTIONS") {
      res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
      return res.status(200).json({});
    }
    next();
  });

const router = Express.Router();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));

mongoose.connect("mymongodatabase");
const connection = mongoose.connection;

connection.once('open', () => {
   console.log('MongoDB database connection established successfully!');
});

router.route('/login').post((req, res)=>{
     let usuarioData = new User(req.body);
     User.findOne({usuario:usuarioData.usuario}, (err, usuario)=>{
       if(err){
            return next(new Error('Could not load document')); 
       }else{
            if(!usuario ||(usuario.senha!==usuarioData.senha)){
                res.status(401).send('Email ou senha inválida')
            }else{
                res.status(200).send(usuario);
            }
       }
   });
});

Everything was working perfectly fine when running both the API and frontend locally, but once I deployed the API on the cloud, I started encountering a "CORS header 'Access-Control-Allow-Origin' missing" error. Is there something additional I need to do since it's now on the cloud? Any help or guidance on this would be greatly appreciated. Thank you!

Answer №1

Newest

There is no need to manually configure it in the code.

https://i.stack.imgur.com/Leg6C.png

You can simply set up CORS within the portal to achieve the same functionality.

https://i.stack.imgur.com/T5k2c.png

If you only require access for

https://myazureapplication.azurerewebsites.net
, you can specify that URL. To allow access for all, use *.

PREVIOUS

Use the following code snippet to permit all websites to access the API during testing. Ensure that the specified URL

https://myazureapplication.azurerewebsites.net
is accurate.

app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  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

IISnode is failing to handle the transmission of a post request containing a significant amount of data within the request body when deployed on I

I currently have a client application built using ASP.net and powered by Nodejs & express, hosted on IIS version 10 in Windows Server 2016. Recently, when I send a post request with a large amount of data in the request body to an API endpoint, it returns ...

Guide on sending a push notification using "npm request" to the Ionic API

I attempted to send a push notification through the Ionic API using "npm request". Here is my code: var request = require('request'); var token = '................'; var title = escapeJson('title 123'); var message = escapeJ ...

What is the sequence of the middlewares for error handling and handling of 404 errors?

The express.js website has confused me with contradictory statements regarding error-handling middleware. According to one page, you should define error-handling middleware last, after other app.use() and routes calls. However, another page states that you ...

"Can someone explain the process of obtaining the chat invite link that allows a member to join using Node Telegram Bot API's #chatmemberupdated function

I'm currently working on a Telegram bot and I need to retrieve the chat invite link when a member joins a group. I've been using the node telegram bot API in NodeJS and following the "chatMemberUpdated" method as outlined in the official Telegram ...

Unable to successfully upload a file in nestJS due to unreliable network conditions

I have successfully set up a controller with a route for file uploads using axios. The implementation includes utilizing FileInterceptor. Everything functions properly, however, when I enable network throttling in the browser, the uploader ceases to work. ...

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

What is the best way to locate a member using a particular nickname?

Is there a way to search for a user by their unique nickname within a particular server? ...

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

What are some effective ways to integrate flow in Cypress testing?

Exploring the integration of Flow into a React application tested with Cypress involves using a web preprocessor plugin with a flow preset. Firstly, the preprocessor is coded in ./cypress/plugin/index.js: const webpack = require('@cypress/webpack-pre ...

Could it be that the function is returning undefined because console.log is executing before the result is actually returned? Perhaps a promise

There is a function located in another file that I need to extract the response from and perform an action based on that response before completing my controller function. This is the snippet of code from the external file: exports.counter = function(com ...

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Converting a string parameter into a JSON stringified object in Express.js

Struggling with creating a query parameter to stringify a JSON object. Does anyone have any tips or solutions? ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

Trouble arises when trying to configure webpack and install npm packages on Ubuntu systems

Recently, I encountered a sudden issue in my project that caused it to repeat and crash in Chrome: https://i.stack.imgur.com/pkVlA.png To resolve the issue, I decided to downgrade some of my packages and also downgraded my npm version to 6.6.0 which prov ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...