sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.
https://sanic.dev
MIT License
18k stars 1.54k forks source link

HEADERS dont work AXIOS #1758

Closed johndiego closed 4 years ago

johndiego commented 4 years ago

My code don't work with axios and vuejs , This is correct implementations? I like'd make without libs !! Thanks for advanced !!

import os,requests
from services.xml import dict2xml
from faker import Faker
from sanic import Blueprint
from ext.config import config
from Crypto.Cipher import AES
from .base import SimpleView
from pbkdf2 import PBKDF2,crypt
from ext.db import db 
from sanic.exceptions import Unauthorized,abort
from models.base import User
from playhouse.shortcuts import model_to_dict, dict_to_model
from sanic.views import HTTPMethodView,CompositionView
import jwt,datetime ,os,dicttoxml
from sanic.response import json,text,html,raw
from .decorators import token

users_bp = Blueprint('users',url_prefix='/users' )

async def main(request): 
    return json({"response": "REFRESHG"}) 

users_bp.add_route(main,methods=['POST','OPTIONS'],uri='/1' ,name='t2')

group = Blueprint.group(users_bp)

@group.middleware('request')
# @token()
async def group_middleware(request):
    pass

@group.middleware('response')
async def print_on_response(request, response):
    # print(response)
    print(request.headers)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    print(response.headers)

In console


<Header('Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type,Authorization', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS')>
[2020-01-07 01:44:18 -0300] - (sanic.access)[INFO][172.21.0.1:34762]: OPTIONS http://localhost:9000/users/1  200 23
[2020-01-07 01:44:29 -0300] [1575] [INFO] Stopping worker [1575]
[2020-01-07 01:44:29 -0300] [1575] [INFO] Server Stopped
[2020-01-07 01:44:30 -0300] [1582] [INFO] Starting worker [1582]
<Header('host': 'localhost:9000', 'connection': 'keep-alive', 'content-length': '56', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'cache-control': 'no-cache', 'origin': 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop', 'postman-token': '212d44c4-a640-9e1a-5cf0-9e3f0e7a309a', 'content-type': 'application/json', 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7')>
<Header('Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type,Authorization', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS')>
[2020-01-07 01:44:30 -0300] - (sanic.access)[INFO][172.21.0.1:34866]: OPTIONS http://localhost:9000/users/1  200 23
ahopkins commented 4 years ago

How is your application deployed? Do you have any proxy layers in front of it?

johndiego commented 4 years ago

in Frontend

<script>
import axios from 'axios'
export default {
  name: 'PageIndex',
   methods: {
      login: function () {
           let postData = {
            username:'master',
            password: 'Password@1'
          };

           axios.post('http://172.21.0.4/users/1/', postData )
            .then((res) => {
              console.log(res)
          })
          .catch(function (error) {
            console.log(error)
          })
          .finally(function () {

          })

    }
  },

}
</script>
Tronic commented 4 years ago

I think you need https://pypi.org/project/Sanic-Cors/ to respond to OPTIONS requests correctly. If the browser doesn't know of CORS status, it won't run you POST request directly but first checks for the headers, and without Sanic CORS extension (or handling OPTIONS manually) it will get 404 instead.

johndiego commented 4 years ago

how make handling OPTIONS manually?

ahopkins commented 4 years ago

Take a look at my answer to your question on #1759. I think this is what you need.

NumesSanguis commented 4 years ago

OP's issue, not the header part, but the Sanic server not seeing the postData, might be related to the discussion here (I have the same issue): https://community.sanicframework.org/t/sanic-cant-recognize-post-request/498

Seems like Sanic cannot handle JSON formatted data, as opposed to url-based keywords?

ahopkins commented 4 years ago

Sanic has no problem with query params or JSON data. Please see my response to your post.