i am trying to post data to server using axios. I can hit GET request but having issues in POST.
# i am using CORS
app = Flask(__name__, static_url_path='',
static_folder='web/static', template_folder='web/templates')
CORS(app)
#flask server code
@app.route('/login', methods=['GET', 'POST'])
def login():
print('hi')
global logingStatus
global currentUser
if request.method == 'POST':
result = db.login(request.form['username'], request.form['password'])
if result == 'success':
logingStatus = True
currentUser = db.getUserObj(request.form['username'])
# print(type(currentUser), '<----')
return redirect(url_for('dashboard'))
else:
return result
else:
logingStatus = False
return render_template('login.html')
client side code:
axios.post('/login/', {
username: this.username,
password: this.password
}).then(function (response) {
if(response.data.includes('ERROR')) {
this.errorMessage = response.data
this.isError = true
}
}).catch(function (error) {
console.log(error);
});
ERROR:
server console:
127.0.0.1 - - [28/Sep/2020 13:55:04] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [28/Sep/2020 13:55:21] "POST /login/ HTTP/1.1" 405 -
client:
Failed to load resource: the server responded with a status of 405 (METHOD NOT ALLOWED)
What i am doing wrong here ?
Edit:
After answer from @cizario i tried
axios('/login',{...});
# error
Failed to load resource: the server responded with a status of 400 (BAD REQUEST)
I was not sure what was doing wrong. But i not solving my problem.
Also, When i try this:
@app.route('/test', methods=['GET', 'POST'])
def test():
return 'test'
# response: test
# headers
access-control-allow-origin:*
It's working !
Where previous post request it was giving response 400 BAD REQUEST
Why ?
Eidt 2:
Ok i found the problem it's related to how i access data from request where i should use request.json['username'] instead of request.form['username'] (which causing 400) (in this context). Also, different rout path on both side was causing 405.
just delete the trilling slash in
axios.post('/login', {..})
because you defined login
route with out /
at the end in
@app.route('/login', methods=['GET', 'POST'])