【问题标题】:Error when trying to connect to API in Azure but origin is allowed尝试连接到 Azure 中的 API 但允许来源时出错
【发布时间】:2020-12-09 14:23:04
【问题描述】:

所以,我在 Azure 中有两个 Web 应用程序,一个是前端,一个是 API。前端通过这段代码连接API:

@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 中,我有这个,用户是猫鼬模型:

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 header 'Access-Control-Allow-Origin' missing”错误。自从它在云上之后,我还需要更多东西吗?提前感谢您的帮助。

【问题讨论】:

    标签: node.js azure express cors


    【解决方案1】:

    最新

    不需要在代码中配置。

    你只需在portal中配置CORS,就可以实现同样的功能。

    如果你只想https://myazureapplication.azurerewebsites.net 访问,你可以添加它。总之,只需添加*

    私人

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多