简体   繁体   中英

http post request from Angular to Express server causes 404 error

I'm making a request to Azure function on local

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

On my express server I'm adding cors to response

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

But when I send request I get this error :

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.

the preflight request is not passing

You could try to remove the extra slash from

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

and so it becomes:

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

Also, as a sidenote, I have not seen your API router, and so maybe there is an extra slash or missing slash in there. Another thing I have noticed is that you're importing an entire folder (?) for your routers so make sure that you are importing a file at once. (i have not seen that, so this might not be true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM