reactjscorsflask-restplus

fetch always pass with OPTIONS method


I made API server with flask-restplus.

Also use cors module for avoid CSP issue.

And frontend is React.js.

My code is here.

class ArticleList(Resource):
    def post(self):
        print(1)
        return {"status":"true", "result":"article write success"}, 200

React.js code is here.

_writeArticle = () => {
    const { title, body, tags, password } = this.state;
    const data = {title: title, body: body, tags: tags, password: password};
    fetch("http://127.0.0.1:5000/article/", {
        method: "POST",
        mode: "cors",
        headers: {
            "Content-Type": "application/json"
        },
        body: data
    })
    .then(res => {
        if(res.status === 200) {
            return <Redirect to='/' />
        } else {
            alert("error");
        }
    })
    .catch(err => console.log(err))
}

I defined method to POST. But, it request with OPTIONS method.

After searched in google, that issue cause by CORS.

So I defined cors to main code like this.

from flask import Flask
from flask_restplus import Api, Resource
from api.board import ArticleList, Article
from flask_restplus import cors

app = Flask(__name__)
api = Api(app)
api.decorators=[cors.crossdomain(origin='*')]

api.add_resource(ArticleList, '/article')
api.add_resource(Article, '/article/<int:article_no>')

if __name__ == '__main__':
    app.run(debug=True)

But it still request with OPTIONS.

How can I solve this issue?


Solution

  • That OPTIONS request is called pre-flight request.
    Under some circumstances relating to CORS the web browser will first send a pre-flight request to server to check if your domain is allowed to make requests to the server or not. If the server says yes then your actual POST request will be sent. Otherwise, no additional requests will be sent and the web browser will spit an error at you.

    Here is documentation on pre-flight request:
    https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1#preflight-requests

    And according to the documentation:

    The pre-flight request uses the HTTP OPTIONS method.