Felix Labelle
Felix Labelle

Reputation: 153

Fetch POST request failing: CORS header

Below is code which sends a post request to a rest API also hosted locally.

const URL ='http://localhost:5000/api/v1.0/tasks/'

function setHIT(HIT_state){
console.log("Sending HIT")
fetch(URL, {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: 'Example',
    lastname: 'Example'
  })
})
.then( (response) => { 
   console.log(response)
});

}

Previously I was getting CORS request errors, but solved it by disabling Chromium's web security option. GET requests work, however when the code above is called the website receives the following response:

Response {type: "cors", url: "http://localhost:5000/api/v1.0/tasks/", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "NOT FOUND"
type: "cors"
url: "http://localhost:5000/api/v1.0/tasks/"
__proto__: Response

The odd things is that there are some requests logged in a database, which means it worked at some point. However I'm not sure what has changed since. What am I missing?

Upvotes: 1

Views: 1364

Answers (2)

Mr Coder
Mr Coder

Reputation: 523

your code structure using a flask cors you should know that.

from flask import Flask
from flask_cors import CORS

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app = Flask(__name__)
CORS(app)

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world! this is Handel cors with all route URL  you"

Upvotes: 1

Mr Coder
Mr Coder

Reputation: 523

what is your backed API?

header('Access-Control-Allow-Origin: http://localhost:5000');

if there is you managing post header from server-side ACL then you need to define a header like Access-Control-Allow-Origin: *
* means all domain

Upvotes: 0

Related Questions