尝试连接到Azure中的API但允许来源时出错 [英] Error when trying to connect to API in Azure but origin is allowed

查看:52
本文介绍了尝试连接到Azure中的API但允许来源时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在Azure中有两个Web应用程序,一个是前端,一个是API.前端通过以下代码与API连接:

So, I have two web apps in Azure, one is the frontend and one is an API. The frontend connects with the API through this 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);
  }
}

在API中,我有这个,其中User是猫鼬模型:

And in the API, I have this, with User being 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);
            }
       }
   });
});

当然,当我同时在本地运行他的API和前端时,它的工作原理就像一个魅力,但是当我部署API时,我会收到"CORS标头'Access-Control-Allow-Origin'missing".错误.自从它在云上以来,我还需要其他东西吗?预先感谢您的帮助.

Sure enough, when I run both he API and the frontend locally it works like a charm, but when I deploy the API, I get a "CORS header 'Access-Control-Allow-Origin' missing" error. Do I need something more since its on cloud? Thanks in advance for any help.

推荐答案

最新

无需在代码中对其进行配置.

Newest

Don't need to configure it in code.

您只需在门户网站中配置 CORS ,就可以实现相同的功能.

You just configure CORS in portal, you can achieve the same function.

如果您只想访问 https://myazureapplication.azurerewebsites.net ,则可以添加它.对于所有内容,只需添加 * .

If you just want https://myazureapplication.azurerewebsites.net access, you can add it. For all, just add *.

重要

请使用此代码允许所有网站访问该API进行测试.确保您指定的 https://myazureapplication.azurerewebsites.net 网址没有错误.

Please use this code to allow all websites to access the api for testing. Make sure that the URL you specify https://myazureapplication.azurerewebsites.net is not wrong.

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();
});

这篇关于尝试连接到Azure中的API但允许来源时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆