0

I am getting this error when trying to send post request using my localhost api :

Access to fetch at 'http://127.0.0.1:8000/my-api/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

here is my code:

const SubmitContact = async (e)=>{
    e.preventDefault()
    const contact = {contact_name,contact_email,contact_body}
    fetch("http://127.0.0.1:8000/my-api/",{
      method: "POST",
      header: {
        "Accept": "application/json",
        "Content Type":  "application/json",
      },
      body: JSON.stringify(contact)
    }).then((result)=>{
      console.warn(result)
    })
  }

Why I can't send post request where I am doing mistake? my api also working in post man so I think I might be doing any mistake in my javascript code.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
hawaj
  • 296
  • 3
  • 12
  • The problem is likely to be with the `localhost:3000`. Try adding it to allowed URLs, or use `http://127.0.0.1:3000`. – Shahriar Jun 06 '22 at 09:38

1 Answers1

0

This is the CORS issue. Browser won't let you request another domain by default (security reasons). Postman doesn't have that mechanism and that's why you can request your API endpoint from Postman.

I don't know which language and lib you are using to develop your API but this is how it has to be done with express.js https://expressjs.com/en/resources/middleware/cors.html. You can enable all CORS requests in development(shouldn't be used in production) or you can setup origin to localhost.

let corsOptions = {
  origin: 'http://localhost:3000',
}

In production, you should set up the real origin.

Alen Šljivar
  • 334
  • 2
  • 9