I'm trying to send file with Content-Type: multipart/form-data and i catch an error:
** (Plug.Parsers.ParseError) malformed request, a MatchError exception was raised with message "no match of right hand side value: false"
(cowboy) /home/erlan/Documents/Work/Erlang/Elixir/api_pager/deps/cowboy/src/cowboy_req.erl:735: :cowboy_req.init_multipart/1
(cowboy) /home/erlan/Documents/Work/Erlang/Elixir/api_pager/deps/cowboy/src/cowboy_req.erl:673: :cowboy_req.part/2
(plug) lib/plug/adapters/cowboy/conn.ex:76: Plug.Adapters.Cowboy.Conn.parse_req_multipart/3
(plug) lib/plug/parsers/multipart.ex:17: Plug.Parsers.MULTIPART.parse/5
(plug) lib/plug/parsers.ex:212: Plug.Parsers.reduce/4
(api_pager) lib/api_pager/endpoint.ex:1: ApiPager.Endpoint.phoenix_pipeline/1
(api_pager) lib/plug/debugger.ex:123: ApiPager.Endpoint."call (overridable 3)"/2
(api_pager) lib/api_pager/endpoint.ex:1: ApiPager.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /home/erlan/Documents/Work/Erlang/Elixir/api_pager/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
Controller.ex:
def upload_user_avatar(conn, %{"upload_file" => upload_file}) do
IO.inspect(upload_file)
json(conn, %{"message" => "Action will created, but file uploading still not working..."})
end
There is some screenshots:
Request Settings
Response from server
really don't know 'cuz of what it happens... Have any ideas?
Related
i am using the new RestSharp V107 version with net 5.0.
I am calling a custom Web API. This Web APi, when the request is not authorized responses with an httpcode 401 and this information in the body (extracted from a request made in Postman)
{
"timestamp": "2022-03-30T12:17:18.558462",
"message": "Unauthorized",
"clazz": "com.mycompany.login.service.impl.AuthenticationServiceImpl",
"method": "authenticate",
"lineno": 64,
"path": "/login"
}
With RestSharp v107 i get an exception, with the message "Request failed with status code Unauthorized", but i can't get the data (or the original 401 Unauthorized http code).
I have tried this in the code, with no luck
var optionsbase = new RestClientOptions("http://mycompany")
{
ThrowOnAnyError = true,
FailOnDeserializationError = true,
ThrowOnDeserializationError = true,
};
Is there any way to get the message in the body when 401 Status is received?
Is there any way to obtain the original message and exception code (in my code i was catching the exception, chceking the status code 401 and saving the info in the body for log)
Actually, the best way is not to force RestSharp to throw but to inspect the response instead. The RestResponse object contains the response content and the response code.
That's the code that calculates the exception:
=> httpResponse.IsSuccessStatusCode
? null
#if NETSTANDARD
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
#else
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode);
#endif
You can see that when you use .NET Core 3.1+ or .NET 5+, you will also get the status code in the exception, but .NET Standard doesn't support that. You still get the status code in the exception message. However, there's no way to include the response content in the exception.
POST request without body parameter gives a JSON parse error. Mentioned the error below.
API Call
api.post('notification/seen')
Error:
{"message":{"name":"SyntaxError","msg":"Unexpected token n in JSON at position 0","stack":"SyntaxError: Unexpected token n in JSON at position 0\n at JSON.parse ()\n at createStrictSyntaxError (/app/node_modules/body-parser/lib/types/json.js:158:10)\n at parse (/app/node_modules/body-parser/lib/types/json.js:83:15)\n at /app/node_modules/body-parser/lib/read.js:121:18\n at invokeCallback (/app/node_modules/raw-body/index.js:224:16)\n at done (/app/node_modules/raw-body/index.js:213:7)\n at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:273:7)\n at IncomingMessage.emit (events.js:327:22)\n at IncomingMessage.EventEmitter.emit (domain.js:486:12)\n at endReadableNT (_stream_readable.js:1327:12)\n at processTicksAndRejections (internal/process/task_queues.js:80:21)"},"level":"error","timestamp":"2021-09-28T06:29:19.577Z"}
Swagger API structure
/notification/seen:
post:
tags:
- Notification
responses:
204:
description: Update Seen Notification Success
401:
description: Access Token Missing/Expired
500:
description: Something went wrong!
If same API I call with adding dummy body as below with changing the Swagger API structure I am not getting the error.
API Call
api.post('notification/seen',{id:"data"})
Swagger API structure
/notification/seen:
post:
tags:
- Notification
parameters:
- in: body
name: body
schema:
type: object
responses:
204:
description: Update Seen Notification Success
401:
description: Access Token Missing/Expired
500:
description: Something went wrong!
And also if I change POST to GET request then also I am not getting the error.
How to fix the error with the POST request without a body parameter?
I'm running a server with clojure on localhost:3000. The server talks to the client, which is a react native app that's using axios to talk to the server. However the communication with the server is returning a 403 error.
Call to the server:
export const invest = (itemid, amount) => async dispatch => {
console.log("investing in actions")
const domain = 'localhost:3000'
const res = axios.post(domain + '/api/invest', {itemid: itemid, amount: amount});
console.log("response is", res)
dispatch({ type: INVESTED, payload:res.data});
}
Server contains a reitit route called "/api/invest", and this route will call a function called featured/invest. But instead I'm getting a 403 error in the client:
(ns humboiserver.routes.home
(:require
[humboiserver.layout :as layout]
[clojure.java.io :as io]
[humboiserver.middleware :as middleware]
[ring.util.response]
[ring.util.http-response :as response]
[humboiserver.routes.featured :as featured]))
(defn home-page [request]
(layout/render request "home.html" {:docs (-> "docs/docs.md" io/resource slurp)}))
(defn about-page [request]
(layout/render request "about.html"))
(defn home-routes []
[""
{:middleware [middleware/wrap-csrf
middleware/wrap-formats]}
["/" {:get home-page}]
["/api"
["/about" {:get about-page}]
["/featured" featured/get-featured]
["/invest" featured/invest]
]
])
Even the invested prn statement isn't printed in the logs.
;; featured/invest function.
(defn response [data & [status]]
{:status (or status 200)
:headers {"Content-Type" "application/json"
"Access-Control-Allow-Headers" "Content-Type"
"Access-Control-Request-Method" "GET, OPTIONS"
"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Credentials" true
}
:body (pr-str data)})
(defn invest [req]
(prn "invested")
(response (db/find "featured" {})))
403 error:
[Warning] Possible Unhandled Promise Rejection (id: 0): (AppEntry.bundle, line 42288)
Error: Request failed with status code 403
createError#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:156390:26
settle#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:156380:25
handleLoad#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:156280:15
dispatchEvent#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:32753:31
setReadyState#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31822:27
__didCompleteResponse#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31653:29
emit#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:7566:42
__callFunction#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3195:36
http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2927:31
__guard#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3149:15
callFunctionReturnFlushedQueue#http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2926:21
callFunctionReturnFlushedQueue#[native code]
http://localhost:19000/debugger-ui/debuggerWorker.aca173c4.js:4:907
How to fix this error?
Hi I think you need to send an Anti-forgery token if I'm not mistaken...
https://github.com/ring-clojure/ring-anti-forgery
You can use curl to test accessing your server via the command line
I'm trying to get x-editable working (to allow inline form edits), using Rails 3.2
When I receive the post from the browser via AJAX, I need to be able to validate the form input and send back a response.
If its successful, I just need:
render :nothing => true
and this works ok.
If unsuccessful, according to their documentation I need to send back the equivalent of this PHP snippet:
header('HTTP 400 Bad Request', true, 400);
echo "This field is required!";
I cannot figure out how to do this in Rails.
If I try a simple render :status => 400, then my terminal output looks as follows:
Rendered text template (0.0ms)
Completed 200 OK in 34ms (Views: 1.3ms | ActiveRecord: 1.5ms)
And I can find no information on how to combine a 400 error with an actual message
How can I do this?
Try this:
render text: "This field is required!", status: :bad_request
What you're after is:
head :no_content, :status => :bad_request
This makes it explicit that you’re only generating HTTP headers
That PHP example doesn't include "This field is required!" in the response, instead it's printed out.
You'll want to respond with just an HTTP header with status code 400 Bad Request, as seen in:
header('HTTP 400 Bad Request', true, 400);
In Rails you can use this:
head :bad_request
# or
head 400
Or this, but it's less explicit to the reader that you're generating just the header:
render nothing: true, status: :bad_request
# or
render nothing: true, status: 400
If you do want to include a body with text in the response (so not just a header):
render text: "This field is required!", status: :bad_request
# or
render text: "This field is required!", status: 400
I get error when uploading file via swfupload in my rails application. The weird things:
The Error appear when I access the application with ipaddress instead of localhost..
I tried upload file with normal uploader (basic), and it's success without error..So I think the upload was fine.
So how to fix it??..should I show the error messages??
Thanks..
Error Message:
error, env =
{"CONTENT_LENGTH"=>"367350",
"CONTENT_TYPE"=>"multipart/form-data;
boundary=----------------------------a19e5ae4ad3b", "GATEWAY_INTERFACE"=>"CGI/1.1",
"PATH_INFO"=>"/documents.js",
"QUERY_STRING"=>"",
"REMOTE_ADDR"=>"192.168.0.112",
"REMOTE_HOST"=>"fallz",
"REQUEST_METHOD"=>"POST",
"REQUEST_URI"=>"http://www.fallz.com:3000/documents.js",
"SCRIPT_NAME"=>"",
"SERVER_NAME"=>"www.fallz.com",
"SERVER_PORT"=>"3000",
"SERVER_PROTOCOL"=>"HTTP/1.1",
"SERVER_SOFTWARE"=>"WEBrick/1.3.1
(Ruby/1.9.2/2011-02-18)",
"HTTP_HOST"=>"www.fallz.com:3000",
"HTTP_USER_AGENT"=>"Shockwave Flash",
"HTTP_CONNECTION"=>"Keep-Alive",
"HTTP_CACHE_CONTROL"=>"no-cache",
"HTTP_ACCEPT"=>"text/*",
"rack.version"=>[1, 1],
"rack.input"=>#,
"rack.errors"=>#>,
"rack.multithread"=>false,
"rack.multiprocess"=>false,
"rack.run_once"=>false,
"rack.url_scheme"=>"http",
"HTTP_VERSION"=>"HTTP/1.1",
"REQUEST_PATH"=>"/",
"action_dispatch.parameter_filter"=>[:password,
:password, :password_confirmation],
"action_dispatch.secret_token"=>"8c1eebbf7a4a0611ed20ae08f05cc32d552cb8e3fe9248a65af475e5b5cd50ef1efe3429c49b65e09cce4d61058e354beaaa161810c0e29717df72ff511ac8f2",
"action_dispatch.remote_ip"=>192.168.0.112,
"rack.request.query_string"=>"",
"rack.request.query_hash"=>{"Filename"=>"Firefox_wallpaper.png", "authenticity_token"=>"%2F2dkUcfOutquj4AG9xjYMcF%2BsfSesSXEwp70MD1itoY%3D",
"Filedata"=>{:filename=>"Firefox_wallpaper.png", :type=>"application/octet-stream",
:name=>"Filedata",
:tempfile=>#,
:head=>"Content-Disposition:
form-data; name=\"Filedata\";
filename=\"Firefox_wallpaper.png\"\r\nContent-Type:
application/octet-stream\r\n"},
"Upload"=>"Submit Query"},
"rack.request.form_input"=>#,
"rack.request.form_hash"=>{"Filename"=>"Firefox_wallpaper.png", "authenticity_token"=>"%2F2dkUcfOutquj4AG9xjYMcF%2BsfSesSXEwp70MD1itoY%3D",
"Filedata"=>{:filename=>"Firefox_wallpaper.png", :type=>"application/octet-stream",
:name=>"Filedata",
:tempfile=>#,
:head=>"Content-Disposition:
form-data; name=\"Filedata\";
filename=\"Firefox_wallpaper.png\"\r\nContent-Type:
application/octet-stream\r\n"},
"Upload"=>"Submit Query"}}