3

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?

Hide
  • 3,199
  • 7
  • 41
  • 83
  • 1
    This is the browser who make this option request, and it's for security. You have to change the server to an state which accept option request. – jsDevia Aug 20 '18 at 03:54
  • 3
    when the browser make a options request, you need to ensure your server returns 200 ok and set Access-Control-Allow-Origin header appropriately in response header. You cannot bypass the options request since it is automatically made by the browser – cdoshi Aug 20 '18 at 04:06

2 Answers2

9

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.

Cù Đức Hiếu
  • 5,569
  • 4
  • 27
  • 35
0

here is my solution,

from flask_cors import CORS


app = Flask(__name__)
CORS(app, supports_credentials=True)
  • Your answer could be improved with supporting information and explanation for how this answers the question – Harrison May 12 '23 at 09:06