Axios post request is being denied by flask made api. CORS error coming up [duplicate] - reactjs

This question already has an answer here:
cors enable in Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
(1 answer)
Closed 2 years ago.
I am trying to add user from my react application through an API made with flask. But the post request is getting in error with the following error.
'http://localhost:5000/api/v1.0/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
my axios code is following
const params = {
user_name : '5678234121',
passwd : 'password',
location : 'Kolkata',
pin_code : '700019',
secret_ques: 'What is your mother s maiden name?',
answr : 'aba',
status : 'Active',
remarks : 'test data'
};
const res = await Axios.post(
'http://localhost:5000/api/v1.0/add', params, {
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
});
console.log(res.data);
my flask code is following
#app.route('/api/v1.0/add', methods=["POST"])
def add():
con = None
db = datadir + datafile
try:
_json = request.json
_name = _json['user_name']
_psswd = _json['passwd']
_locatn = _json['location']
_pincd = _json['pin_code']
_secrt = _json['secret_ques']
_ans = _json['answr']
_stat = _json['status']
_remks = _json['remarks']
# validate the received values
if _name and _psswd and _pincd and request.method == 'POST':
#do not save password as a plain text
_hashed_password = base64.b64encode(_psswd.encode("utf-8"))
# save edits
sql = '''INSERT INTO user_mast(user_name, passwd, location, pin_code, secret_ques, answr, status, remarks ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'''
data = (_name, _hashed_password.decode('ASCII'), _locatn, _pincd, _secrt,_ans, _stat, _remks , )
con = sqlite3.connect( db ) # Connection to database
cur = con.cursor()
cur.execute(sql, data)
con.commit()
resp = jsonify({'Status' : 'User added successfully!'})
resp.status_code = 200
else :
resp = jsonify ({'Status' :'Mandatory fields: Name,Password,Pincode missing..'})
resp.status_code = 502
except sqlite3.Error as e:
resp = jsonify({'Status' :'Database Error'})
resp.status_code = 500
except Exception as e:
print(e)
resp = jsonify({'Status' :'Unknown Error : Contact Administrator'})
resp.status_code = 501
finally:
cur.close()
con.close()
return resp
Please help me to fix the error, going clueless about this.

If you're new to this, I'd recommend just adding Flask-CORS to your application and not futzing around with the headers.

Related

Cross-Origin Request Blocked and Preflight executes View Django-project

In my Django and React project, I am trying to make a registration request which is failing due to a missing "Access-Control-Allow-Origin" header, resulting in a 504 error. The problem I believe I am facing is that the preflight (OPTIONS) request is already executing the View, which is causing issues with permissions for the subsequent POST request.
Jan 21 10:11:20 AllKids python3[155868]: [21/Jan/2023 09:11:20] "OPTIONS /user/register/ HTTP/1.0" 200 0
Jan 21 10:11:20 AllKids python3[155868]: in View
I am not sure why this issue is only occurring on this View, as all other views are working correctly.
Jan 21 10:21:40 AllKids python3[156001]: [21/Jan/2023 09:21:40] "POST /user/validatePassword/ HTTP/1.0" 200 613
It is worth noting that the OPTIONS request is returning a 200 status code. I would like to share the following code with you for further analysis:
let formData = {
password: password,
username: username,
email: email,
};
console.log(formData);
let request = await fetch(
`${process.env.REACT_APP_BACKEND_URL}/user/register/`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
}
);
console.log(response, 'WTF');
let response = await request.json();
The "WTF" line is not being reached since I am not getting the response... For comparison, here is an function that works perfectly fine(login):
let formData = { password: password, email: email };
let request = await fetch(
`${process.env.REACT_APP_BACKEND_URL}/user/validatePassword/`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
}
);
let response = await request.json();
here are my Django settings:
INSTALLED_APPS = [
...
"corsheaders",
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
here is the View which is being executed on the preflight request:
#api_view(["POST"])
def registerUser(request):
print("In Function")
body = returnContent(request)
try:
CustomUser.objects.get(email=body["email"])
return Response("Email already in use!")
except:
if len(body["username"]) < 4:
return Response("Username should be at least 3 characters long.")
if body["username"][0].isdigit():
return Response("Username should not start with a digit.")
if len(body["password"]) < 7:
return Response("Password must be at least 6 characters")
randomToken = random.randrange(100000, 999999)
user = CustomUser.objects.create_user(
username=body["username"], email=body["email"], password=body["password"], currentVerificationToken=randomToken)
sendEmailVerification(
user.username, user.currentVerificationToken, user.email)
user = CustomUserLoggedSerializer(user, many=False)
return Response(user.data)
and this would be the login request where everything works just fine...:
#api_view(["POST"])
def validatePassword(request):
body = returnContent(request)
try:
password = body["password"]
email = body["email"]
except:
return Response("No Email or Password provided")
try:
user = CustomUser.objects.get(email=email)
except:
return Response("Invalid email")
user = authenticate(request, email=email, password=password)
if user is not None:
if user.twoFactorVerification:
setattr(user, "currentVerificationToken",
random.randrange(100000, 999999))
user.save()
sendEmailVerification(
user.username, user.currentVerificationToken, user.email)
return Response("Two-Factor Authentication Required")
login(request, user)
user = CustomUserLoggedSerializer(user, many=False)
return Response(user.data)
else:
return Response(False)

wkhtmltopdf reported an error: Exit with code 1 due to network error: ContentNotFoundError

good day, please im having this error when i click Export to pdf button…………………
‘’’
views.py
#login_required(login_url='loginpage')
#cache_control(no_cache=True, must_rev alidate=True, no_store=True)
def exportToPdf(request, pk):
c = get_object_or_404(candidate, id=pk)
cookies = request.COOKIES
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'cookie' : [
('csrftoken', cookies ['csrftoken']),
('sessionid', cookies ['sessionid'])
]
}
pdf = pdfkit.from_url('http://127.0.0.1:8000/'+str(c.id), False, options = options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-disposition'] = 'attachment; filename=candidate.pdf'
return response
urls.py
path('int:pk/exporttopdf/', views.exportToPdf, name='exporttopdf'),
‘’’

400 Error Code on callout using User-Password oAuth FLow

I am getting bad request error while trying to get token using this piece of code:
String clientId = '3MVG9t0sl2P.pByrrjfFFCVMbFHMMMm.qRQK6yRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ';
String clientSecret = '0ABB12793CB8CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404';
String username='mp7mp#gmail.com';//salesforce username
String password='Yg8#';//EUe4eHjMxXb8UFco1SPcpsZL9';//salesforce password
// Generating the Access Token
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit
req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
Http http = new Http();
HTTPResponse response = http.send(req);
if(response.getStatusCode() == 200){
system.debug('## Successfully retrieving access token' );
map<string,Object> resultMap = (map<string,Object>)JSON.deserializeUntyped(response.getBody());
accesstoken = (String)resultMap.get('access_token');
instanceURL = (String)resultMap.get('instance_url');
system.debug('Accesstoken'+ accesstoken );
system.debug('instanceURL'+ instanceURL);
//step 2 : use the token for the salesforce api call
}
else{
system.debug('## Could not retrieve the access token' + response.getStatusCode() + '--'+ response.getStatus());
system.debug('## response status :' + response.getStatus());
system.debug('## response message :' + response.getBody());
}
This is the request:
grant_type=password&client_id=3MVG9t0sl2P.pByrrjfFFCm.qRQK6yo58pRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ&client_secret=0ABB12793738CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404&username=mp7504.mp#com&password=Ygua8#

getting google oauth to work with flask, react, postgresql. keep getting internal server error and cors errors

I'm trying to get google oauth to work with flask and react. When I run the server and try to log in, the google sign-in window pops up and immediately closes down and I get an internal server error. in my flask terminal I get this error:
raise MissingCodeError("Missing code parameter in response.")
oauthlib.oauth2.rfc6749.errors.MissingCodeError: (missing_code) Missing code parameter in response.
Any thoughts?
app.py
#app.route('/login', methods=['POST'])
#cross_origin()
def login():
google_provider = get_google_provider()
auth_endpoint = google_provider["authorization_endpoint"]
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "/callback",
scope=["openid", "email", "profile"]
)
return redirect(request_uri)
#app.route('/login/callback', methods=['GET', 'POST'])
#cross_origin()
def login_callback():
code = request.json.get("access token")
print("**************")
# print(list(request.args.keys()))
print(request.json)
print("**************")
token, headers, body = client.prepare_token_request(
token_endpoint,
code=code,
authorization_response=request.url,
redirect_url=request.base_url
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
)
client.parse_request_body_response(json.dumps(token_response.json()))
userinfo_endpoint = google_provider["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = request.get(uri, headers=headers, data=body)
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
user_email = userinfo_response.json()["email"]
user_picture = userinfo_response.json()["picture"]
user_name = userinfo_response.json()["given_name"]
user_member_since = datetime.today().strftime('%Y-%m-%d')
else:
print("User email not available or not verified by Google")
user = User(id=unique_id, name=user_name, email=user_email, picture=user_picture, member_since=user_member_since)
if not User.get(unique_id):
User.create(unique_id, user_name, user_email, user_picture, user_member_since)
login_user(user)
redirect(url_for("/new-user-form"))
app.js
googleResponse = (response) => {
const tokenBlob = new Blob([JSON.stringify({access_token: response.accessToken}, null, 2)], {type: 'application/json'});
const options = {
method: 'POST',
body: tokenBlob,
mode: 'cors',
cache: 'default'
}
fetch(`${BASE_URL}/login/callback`, options).then(r => {
if (r.headers.get('Content-Type') === 'text/html; charset=utf-8') {
console.log('error')
return
}
const token = r.headers.get('x-auth-token')
r.json().then(user => {
if (token) {
this.setState({isAuthenticated: true, user, token, message: `${user.name}`})
console.log(token)
}
});
})
}
onFailure = (error) => {
alert(error.data)
}
<Route path='/login'>
<GoogleLogin
clientId={config.GOOGLE_CLIENT_ID}
buttonText="Login"
onSuccess={this.googleResponse}
onFailure={this.onFailure}
/>

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Resources