从Angular到Express服务器的HTTP发布请求导致404错误

时间:2019-12-27 18:14:47

标签: node.js angular express cors

我正在向本地的Azure函数发出请求

url = 'http://localhost:7071/api/saveGraphDataFlow'
save(body) {
  let headers = new HttpHeaders()
  headers.append('Content-Type', 'application/json')
  return this.httpClient.post(this.url, body, { headers: headers }).pipe(
     map(res => {
      return res
    })
  )
}

在我的快递服务器上,我要添加cors来响应

const createHandler = require("azure-function-express").createHandler;
const express = require("express");
const routers = require("./routes/routes");
const app = express();
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");

  next();
});
app.use("/api/", routers);

// Binds the express app to an Azure Function handler
module.exports = createHandler(app);

但是当我发送请求时,出现此错误:

Access to XMLHttpRequest at 'http://localhost:7071/api/saveGraphDataFlow' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

preflight请求未通过

1 个答案:

答案 0 :(得分:0)

您可以尝试从中删除多余的斜杠

app.use("/api/", routers);

因此变成:

app.use("/api", routers);

此外,作为一个旁注,我还没有看到您的API路由器,因此也许其中有一个额外的斜杠或缺少斜杠。我注意到的另一件事是,您正在为路由器导入整个文件夹(?),因此请确保立即导入文件。 (我还没有看到,所以可能不正确)