Could not find starting boundary - aiohttp

🐞 Describe the bug
I am used aiohttp as a client and a server to File Uploads,The server raised an error when I add headers in post request。
Could not find starting boundary b'--dd7db5e4c3bd4d5187bb978aef4d85b1'
💡 To Reproduce
environment
python: 3.7.4
aiohttp: 3.7.4.post0
windows10
server
```python
...
print("Enter form-data")
print("req header: ", request.headers)
data = await request.post()
file_data = data["file"]
```
client
1、Not work
```python
async with aiohttp.ClientSession() as session:
async with session.post(
url='http://{}:{}/mesh/recognize'.format(web_ip, web_port),
data=file_data,
headers={'Content-Type': 'multipart/form-data; boundary=dd7db5e4c3bd4d5187bb978aef4d85b1'}
) as resp:
```
console:
> Enter form-data
> req header: <CIMultiDictProxy('Host': '192.168.102.116:8000', 'Content-Type': 'multipart/form-data; boundary=dd7db5e4c3bd4d5187bb978aef4d85b1', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'User-Agent': 'Python/3.7 aiohttp/3.7.4.post0', 'Content-Length': '364927')>
Could not find starting boundary b'--dd7db5e4c3bd4d5187bb978aef4d85b1'
** predict is Failed **
2、 work
```python
async with aiohttp.ClientSession() as session:
async with session.post(
url='http://{}:{}/mesh/recognize'.format(web_ip, web_port),
data=file_data) as resp:
```
console:
> Enter form-data
>req header: <CIMultiDictProxy('Host': '192.168.102.116:8000', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'User-Agent': 'Python/3.7 aiohttp/3.7.4.post0', 'Content-Length': '364927', 'Content-Type': 'multipart/form-data; boundary=dd7db5e4c3bd4d5187bb978aef4d85b1')>
out: torch.float32
Predict result :tensor([[[0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
[5.0122, 4.7581, 4.8532, ..., 4.7490, 4.6256, 4.8851]]]),
run time is 3054.393768310547ms
** predict is Successed! **

Related

Access a remote api from frontend react.js without any server side code

I am trying to access remote url from fetch/axios post api in react.js. Here is my code in react-
const requestOptions = {
method: 'POST',
crossDomain: true,
mode: 'cors', // no-cors, *cors, same-origin
credentials: 'same-origin', // include, *same-origin, omit
headers:{'Content-Type': 'application/x-www-form-urlencoded',
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer',
body:new URLSearchParams({
'store_id':'storeid',
'store_passwd':'storepass',
'total_amount':100,
'currency':'BDT',
'tran_id':'NF04',
'success_url':"https://tigrow.herokuapp.com",
'fail_url':"https://tigrow.herokuapp.com",
'cancel_url':"https://tigrow.herokuapp.com",
'cus_name':"nizam",
'cus_email':"test#test.com",
'cus_add1':"customer address",
'cus_add2':"customer address",
'cus_city':"Dhaka",
'cus_state':"Dhaka2",
'cus_postcode':"Dhaka",
'cus_country':"Bangladesh",
'cus_phone':"01700000000",
'cus_fax':"01700000000",
'ship_name':"Sha",
'ship_add1':"dhaka",
'ship_add2':"dhaka1",
'ship_city':"Dhaka1",
'ship_state':"Dhaka2",
'ship_postcode':"1000",
'ship_country':"Bangladesh",
'multi_card_name':"mastercard,visacard,amexcard",
'value_a':"ref001_A",
'value_b':"ref002_B",
'value_c':"ref003_C",
'value_d':"ref004_D",
'shipping_method':"No",
'product_name':"Test",
'product_category':"Test Category",
'product_profile':"general"
})
};
fetch(url, requestOptions)
.then(response =>console.log(response))
.then(data => console.log(data));
I want to get data from rempte api in react only, not any server side code. Here my content-type is application/x-www-form-urlencoded. How can I solve this problem only using react.js?
My remote API strictly mentioned that no call from client side code. Developer must need to call the API from server side and after completing the call developer should return the string url, not any json data. I followed the way and done the code in python and got the result. However my frontend was react. Here is the code snippet-
def sslcommerz_payment_gateway(request):
gateway_auth_details = PaymentGatewaySettings.objects.all().first()
settings = {'store_id':gateway_auth_details.store_id,
'store_pass': gateway_auth_details.store_pass,
'issandbox': True} #gateway_auth_details.store_pass, 'issandbox': False}
print(request.POST)
sslcommez = SSLCOMMERZ(settings)
post_body = {}
post_body['total_amount'] =request.POST.get('total_amount')
post_body['currency'] = request.POST.get('currency')
post_body['tran_id'] =unique_transaction_id_generator()
post_body['success_url'] = 'http://127.0.0.1:8000/api/payment/success/'
post_body['fail_url'] = 'http://127.0.0.1:8000/api/payment/faild/'
post_body['cancel_url'] = request.POST.get('cancel_url')
post_body['emi_option'] = 0
post_body['cus_name'] = request.POST.get('cus_name')
post_body['cus_email'] =request.POST.get("cus_email")
post_body['cus_phone'] = request.POST.get("cus_phone")
post_body['cus_add1'] = request.POST.get("cus_add1")
post_body['cus_city'] = request.POST.get("cus_city")
post_body['cus_state'] =request.POST.get("cus_state")
post_body['cus_postcode'] =request.POST.get("cus_postcode")
post_body['cus_country'] = request.POST.get("cus_country")
post_body['shipping_method'] ="NO"#request.POST.get("shipping_method")
post_body['multi_card_name'] = "mastercard,visacard,amexcard,mobilebank,internetbank,othercard"
post_body['num_of_item'] = request.POST.get("num_of_item")
post_body['product_name'] = request.POST.get("product_name")
post_body['product_category'] = request.POST.get("product_category")
post_body['product_profile'] = "Art(Hard Copy/Soft Copy)"
response = sslcommez.createSession(post_body)
print(response)
return 'https://sandbox.sslcommerz.com/gwprocess/v4/gw.php?Q=pay&SESSIONKEY=' + response["sessionkey"]
Finally I got the API response and returned a url.

Using React fetch gives pyramid.exceptions.PredicateMismatch: The resource could not be found

I am writing a React web client that use a REST API to communicate to a Python Pyramid backend. Problem is that only the methods POST and GET works. All other give error on the server. Also I can only use the "Accept' header, all other give the same error:
pyramid.exceptions.PredicateMismatch: The resource could not be found.
It works fine from Android app, using CURL, using Postman, and REST API plugins in browser mode. But for the fetch command in React it do not work.
Server Side:
config.add_route('admin_language_api', '/api/admin/language')
def allow_CORS(config, log):
def add_cors_headers_response_callback(event):
def cors_headers(_, response):
response.headers.update({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '1728000'
})
event.request.add_response_callback(cors_headers)
config.add_subscriber(add_cors_headers_response_callback, NewRequest)
#view_config(route_name='admin_language_api',
request_method='DELETE',
renderer='json')
# #auth.require_api_auth
def delete_language(request):
React side:
export async function PServLanguagePost(languageObj) {
const data = await fetch('http://localhost:6543/api/admin/language', {
method: 'DELETE',
body: JSON.stringify(languageObj)
});
return await data.json();
}
Server ERROR:
2021-05-07 04:53:34,041 INFO [pyramid_debugtoolbar:287][waitress-3] Squashed pyramid.exceptions.PredicateMismatch at http://localhost:6543/api/admin/language
traceback url: http://localhost:6543/_debug_toolbar/31383138393039313238303136/exception
Pyramid dump:
request:
<Request at 0x228d20ffca0 OPTIONS http://localhost:6543/api/admin/language>
attr:
{'environ': {'REMOTE_ADDR': '127.0.0.1', 'REMOTE_HOST': '127.0.0.1', 'REMOTE_PORT': '56013', 'REQUEST_METHOD': 'OPTIONS', 'SERVER_PORT': '6543', 'SERVER_NAME': 'waitress.invalid', 'SERVER_SOFTWARE': 'waitress', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SCRIPT_NAME': '', 'PATH_INFO': '/api/admin/language', 'QUERY_STRING': '', 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.input': <_io.BytesIO object at 0x00000228D35C7040>, 'wsgi.file_wrapper': <class 'waitress.buffers.ReadOnlyFileBasedBuffer'>, 'wsgi.input_terminated': True, 'HTTP_HOST': 'localhost:6543', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0', 'HTTP_ACCEPT': '*/*', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.5', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCESS_CONTROL_REQUEST_METHOD': 'DELETE', 'HTTP_REFERER': 'http://localhost:3000/', 'HTTP_ORIGIN': 'http://localhost:3000', 'HTTP_CONNECTION': 'keep-alive', 'waitress.client_disconnected': <bound method HTTPChannel.check_client_disconnected of <waitress.channel.HTTPChannel connected 127.0.0.1:56013 at 0x228d33c93d0>>, 'webob._parsed_cookies': ({}, ''), 'CONTENT_LENGTH': '0', 'webob.is_body_seekable': True, 'webob._parsed_query_vars': (GET([]), ''), 'webob._cache_control': ('', <CacheControl ''>)}, 'registry': pyramid.registry.Registry({}), 'invoke_subrequest': <bound method Router.invoke_subrequest of <pyramid.router.Router object at 0x00000228D1D07610>>, 'pdtb_id': '32333734333436323130343634', 'finished_callbacks': collections.deque([]), '_headers': <webob.headers.EnvironHeaders object at 0x00000228D33C9B80>, 'pdtb_sqla_queries': [], 'request_iface': <InterfaceClass pyramid.request.admin_language_api_IRequest>, 'response_callbacks': collections.deque([]), 'matchdict': {}, 'matched_route': <pyramid.urldispatch.Route object at 0x00000228D358EA00>, 'root': <pyramid.traversal.DefaultRootFactory object at 0x00000228D33C9C10>, 'view_name': '', 'subpath': (), 'traversed': (), 'virtual_root': <pyramid.traversal.DefaultRootFactory object at 0x00000228D33C9C10>, 'virtual_root_path': (), 'locale_name': 'en', 'exception': <PredicateMismatch at 0x228d35d8160 404 Not Found>, 'exc_info': (<class 'pyramid.exceptions.PredicateMismatch'>, <PredicateMismatch at 0x228d35d8160 404 Not Found>, <traceback object at 0x00000228D3448C40>)}

firebase auth rest api not returning the full body response in arduino ide

i've been stuck in a problem with firebase auth rest api in arduino ide, the following code returns code 200
String url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=" + String(apiKey);
http.setTimeout(5000);
http.begin(url);
http.addHeader("Content-Type", "application/json");
String dataSent = "{\"email\":\"" + String(email) + "\",\"password\":\"" + String(pswd) + "\",\"returSecureToken\":\"true\"}";
int status = http.POST(dataSent);
Serial.println(status);
if (status <= 0)
{
Serial.printf("HTTP error: %s\n",
http.errorToString(status).c_str());
return false;
}
// Read the response.
String payload = http.getString();
Serial.println(payload);
but when i look in my serial monitor the response looks like this:
{
kind: "the kind of response",
localId: "someId",
email: "myEmail",
displayName: "myDisplayName",
idToken: "someIdToken",
registered: "someBoolean",
}
witch aparently is ok but when i try the same http request in postman the response includes also refreshToken and expiresIn
with even more investigation i found that localId from postman is about 980 characters while the localId from my arduino code is only about 680
im trying (and failing) to use the localId to authenticate a request with the firestore api and i think this difference in lenght is what's been buggingme.
could that really be the problem ?
method: "POST",
body: JSON.stringify({
email: enteredEmail,
password: enteredPassword,
returnSecureToken: true,
}),
headers: {
"Content-Type": "application/json",
},
})
NB: Make sure {returnSecureToken: true} is part of your request body

Reactjs to Webapi on ASP.net Core 2.2 fails with error 415 in app but not in Postman

It can do a GET OK, but it just can't do a POST. I have tried all manner of Header combinations. Its to the localhost.
Here is my Reactjs App call
export function saveStaff(data) {
return fetch(baseUrl, {
mode: "no-cors",
method: "POST",
headers: {
Host: "localhost:44370",
Allow: "GET, POST",
Accept: "application/json, text/plain",
"Content-Type": "application/json"
},
body: { Name: "tuesday", Department: "tuesday", visitorcount: 0 } // data // JSON.stringify(data)
})
.then(handleResponse)
.catch(handleError);
}
Here are the headers from Postman this works!
POST /api/StaffNamesAPI HTTP/1.1
Host: localhost:44370
Allow: GET, POST
Content-Type: application/json
Accept: application/json, text/plain
User-Agent: PostmanRuntime/7.16.3
Cache-Control: no-cache
Postman-Token: a5b282c7-24e7-46a6-ba22-4f74a31fa9bd,2232ec6c-b3e9-4e29-88e3-abf63675486c
Host: localhost:44370
Accept-Encoding: gzip, deflate
Content-Length: 122
Connection: keep-alive
cache-control: no-cache
{"Name": "Wednesday TestWithPostman",
"Department": "Groan",
"visitorcount": 0 }
Here is the API Controller
[HttpPost]
[Consumes("application/json")] //https://github.com/aspnet/AspNetCore/issues/4396
public async Task<ActionResult<StaffNames>> PostStaffNames(StaffNames staffNames)
{
_context.StaffNames.Add(staffNames);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStaffNames", new { id = staffNames.Id }, staffNames);
}
My class is simple at this stage
public class StaffNames
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public int VisitorCount { get; set; }
}
And in my startup.cs I have the CORS set up
//https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#ecors
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/",
"http://www.contoso.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Here is my useCors
app.UseCors(MyAllowSpecificOrigins);
//https://stackoverflow.com/questions/52896068/reactasp-net-core-no-access-control-allow-origin-header-is-present-on-the-r
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
Thanks for your help, I have been pondering this for hours!
If you have two projects, you need to set your mode as cors.And I met the same problem of CORS.Finally, I overcome it by removing the / in your original url like
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
//Do not use `http://localhost:3000/`
builder.WithOrigins("http://localhost:3000",
"http://www.contoso.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Configure method:
app.UseCors(MyAllowSpecificOrigins);
React:
return fetch(baseUrl, {
mode: "cors",
method: "POST",
headers: {
Host: "localhost:44370",
Allow: "GET, POST",
Accept: "application/json, text/plain",
"Content-Type": "application/json"
},
body: JSON.stringify({ Name: "tuesday", Department: "tuesday", visitorcount: 0 })
})
For some reason using no-cors mode prevents setting Content-Type header value to application/json and it's set to test/plain by default which causes the issue. After some research I've found out that mode cors works fine for your case, so first of all consider learning more about all those modes and choose most suitable one for you.
And, secondly, you need to add [FromBody] attribute you action parameter in order to allow model binder parse json body on server side. On client side you need to serialize object to json before sending it since fetch doesn't do this for you. The minimal working code looks like this
Controller
[HttpPost]
[Consumes("application/json")]
public IActionResult PostStaffNames([FromBody]StaffNames staffNames)
React
export function saveStaff(data) {
return fetch(baseUrl, {
mode: "cors",
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(handleResponse)
.catch(handleError);
}

Why in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error

I'm making axios call to my php API (which shows user data when a valid token is sent back to API server) and sending a valid jwt token in request header (along with Bearer as prefix) and in the Network's tab its showing that my token is being sent in the header but still it gives me 401 error and returns the Error msg of API that "jwt is empty"...
my API to fetch user data (when valid token is provided) is on http://localhost/Auth/api/validate.php
and client side is on http://localhost:3000
This API is in php and works perfectly fine on Postman. But gives me 401(unauthorized) when I call it in react. I searched this error and everyone says that u should have token in the Request header, I do have it but its not being read by the server and server considers it null so sends me unauthorized error. Please Please help me someone!!!!!
here is the axios API call:
e.preventDefault();
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',token, {
headers: {
'Authorization' : 'Bearer '+token,
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});
Response Headers
> Request URL: http://localhost/Auth/api/validate.php
> Request Method: POST
> Remote Address: [::1]:80
> Status Code: 401 Unauthorized
> Referrer Policy: no-referrer-when-downgrade
> Accept: application/json; charset=UTF-8, */*
> Access-Control-Allow-Credentials: true
> Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With
> Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
> Access-Control-Allow-Origin: *
> Access-Control-Exposed-Header: true
> Authorization Access-Control-Max-Age: 33600
> Connection: Keep-Alive
> Content-Length: 34
> Content-Type: application/json; charset=UTF-8, */*
> Date: Sat, 23 Mar 2019 12:33:00 GMT Keep-Alive: timeout=5, max=99
> Server: Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.3 X-Powered-By:
> PHP/7.2.3
Request Headers:
> Provisional headers are shown Accept: application/json, text/plain, */*
>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
> Content-Type: application/json
> Origin: http://localhost:3000
> Referer: http://localhost:3000/profile
> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
> Request Payload: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
Here is my API validate.php
<?php
// required headers//
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8, */*");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 33600");
header("Content-Length: 144");
header("Accept: application/json; charset=UTF-8, */*");
header("Access-Control-Exposed-Header: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With");
// required to decode bbbb
include_once 'config/core.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/BeforeValidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/ExpiredException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/SignatureInvalidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
// get posted data
$data = json_decode(file_get_contents("php://input"));
// get jwt
$jwt=isset($data->jwt) ? $data->jwt : "";
// if jwt is not empty
if($jwt){
// if decode succeed, show user details
try {
// decode jwt
$decoded = JWT::decode($jwt, $key, array('HS256'));
// set response code
http_response_code(200);
// show user details
echo json_encode(array(
"message" => "Access granted.",
"data" => $decoded->data
));
}
// if decode fails, it means jwt is invalid
catch (Exception $e){
// set response code
http_response_code(401);
// tell the user access denied & show error message
echo json_encode(array(
"message" => "Access denied. Decode fails",
"error" => $e->getMessage()
));
}
}
// show error message if jwt is empty
//gggg
else{
// set response code
http_response_code(401);
// tell the user access denied
echo json_encode(array("message" => "Access denied. Empty"));
}
?>
EDIT
I also tried sending the token without 'Bearer' prefix but it didnt work. On Postman I send a post request (in the body) to my server API like this(which works fine):
{
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNTkiLCJDb21wYW55TmFtZSI6IkVub3VnaCIsIkNvbnRhY3RQZXJzb24iOiJlbm91Z2giLCJDb250YWN0Tm8iOiIzNDM0NCIsImVtYWlsIjoiZUBnbWFpbC5jb20ifX0.o4V6zu8AFBAMoJgRe_jvMoByDK3yDEiF_pxW4ttqpYQ"
}
The php code is expecting JWT token in the body. The token should be in a JSON as shown below.
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',{"jwt":token}, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});

Resources