【问题标题】:CORS issue (Express backend, Angular frontend)CORS 问题(Express 后端、Angular 前端)
【发布时间】:2018-06-12 16:57:53
【问题描述】:

我的前端使用 Angular,后端使用 Express。我遇到了一个 CORS 问题,其中 一个 具有类似配置的几个 api 端点:

无法加载http://localhost:3000/api/deletePost:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 400。

任何帮助将不胜感激。谢谢。

前端代码(web-calls.service.ts)

// Not working

deleteArticle(articleId:string): Observable<any> {
  return this.http.post('http://localhost:3000/api/deletePost', JSON.stringify(articleId), {
    headers: new HttpHeaders().set('Content-Type', 'application/json'),
  }).map(data => {
    if (data["status"] == 200) {
      this.router.navigate(['posts']);
    } else if (data["status"] == 500) {
      // TODO: error message and handling here
      console.log(data);
    }
    return data["status"];
  });
}


// working

createOrUpdatePost(url, articleComplete): Observable<number> {
  return this.http.post('http://localhost:3000/api/updatePost', JSON.stringify(articleComplete), {
    headers: new HttpHeaders().set('Content-Type', 'application/json'),
  }).map(data => {
    if (data["status"] == 200) {
      this.router.navigate(['post' + '/' + data["response"]]);
    } else if (data["status"] == 500) {
      // TODO: error message and handling here
      console.log(data);
    }
    return data["status"];
  });
}

后端代码(app.js)

app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'authorization,Content-Type, X-Requested-With');
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

app.use('/api', api);

还为 app.js 尝试了此配置

function setupCORS(req, res, next) {
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'authorization,Content-Type');
    res.header('Access-Control-Allow-Origin', '*');
    console.log("METHOD: " + req.method);
    if (req.method === 'OPTIONS') {
        console.log('OPTIONS >>>');
        res.status(200).end();
    } else {
        console.log('NOT OPTIONS >>>');
        next();
    }
}
app.all('/*', setupCORS);

后端代码(api.js)

router.post('/deletePost', function (req, res, next) {
    console.log('here here'); // does not print to console
    // other code here
}

router.post('/updatePost', function (req, res, next) {
    console.log('here here'); // prints just fine
    // other code here
}

【问题讨论】:

    标签: angular express


    【解决方案1】:

    有一次我遇到了类似的问题,我记得通过添加这个标题来解决它:Access-Control-Allow-Credentials: true 也许对你有帮助。

    顺便说一句,我建议您在发送数据之前不要使用JSON.stringify()

    更新

    您也可以使用 curl 来调试 CORS,如本问题中所述How can you debug a CORS request with cURL?

    【讨论】:

    • 你能详细说明为什么不使用JSON.stringify()吗?这是最佳实践吗?是不是因为我的数据类型是字符串?
    【解决方案2】:

    显然,JSON.stringify('string') 并不意味着数据类型作为 json 字符串正确发送。

    相反,使用 JSON.stringify(object) 有效。

    经验教训:如果您的数据格式不正确,浏览器控制台上显示的 CORS 错误将无济于事。

    应该是什么

    // changed the method to accept an Article object instead of a string.
    
    deleteArticle(article:Article): Observable<any> {
      return this.http.post('http://localhost:3000/api/deletePost', JSON.stringify(article), {
        headers: new HttpHeaders().set('Content-Type', 'application/json'),
      }).map(data => {
        if (data["status"] == 200) {
          this.router.navigate(['posts']);
        } else if (data["status"] == 500) {
          // TODO: error message and handling here
          console.log(data);
        }
        return data["status"];
      });
    }
    

    【讨论】:

      【解决方案3】:

      您可能希望使用代理来缓解本地服务器上的 CORS,这是在本地开发时处理 CORS 的更好方法。要在您的 Angular 应用程序上设置代理,请创建一个新文件 proxy.config。 json 在您的项目文件夹中与 package.json 并在一起,并将这些行添加到其中:

      {
       "/localapi/*": {
      "target": "http://localhost:4646",
      "pathRewrite": {
        "^/localapi": ""
      },   
      "changeOrigin": true,
      "secure": false,
      "logLevel": "debug"
        }
      }
      

      添加您的本地 api 地址,例如“mydomain/api/”,这样所有带有此 url 的请求都将通过代理发送。接下来修改你的 package.json 并更改“start”的值

      "start": "ng serve --proxy-config proxy.config.json"
      

      现在使用上述命令而不是 ng serve 来启动您的应用,您不会遇到任何 CORS 问题,无需手动为服务器上的每个请求添加自定义标头。

      【讨论】:

        猜你喜欢
        • 2021-12-15
        • 2020-07-10
        • 2022-06-30
        • 2020-07-17
        • 2018-03-11
        • 2021-09-04
        • 2019-09-24
        • 2019-09-16
        • 2018-03-06
        相关资源
        最近更新 更多