NanoHttpd / nanohttpd

Tiny, easily embeddable HTTP server in Java.
http://nanohttpd.org
BSD 3-Clause "New" or "Revised" License
6.94k stars 1.69k forks source link

[Error] Can not use method "POST" #563

Open zrg-team opened 4 years ago

zrg-team commented 4 years ago

I try to handle request POST

try {
            request = fillRequestMap(session, requestId);
        } catch (IOException ioe) {
            return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        } catch (ResponseException re) {
            return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        } catch (Exception ex) {
            return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_HTML, "<html><body><h1>Error</h1>" + ex.toString() + "</body></html>");
        }

Method get request data

private WritableMap fillRequestMap(IHTTPSession session, String requestId) throws Exception {
        Method method = session.getMethod();
        WritableMap request = Arguments.createMap();
        Log.d("QVIProtocol", "Method " + method);
        Map<String, String> headers = session.getHeaders();
        Map<String, String> params = session.getParms();
        Map<String, String> files = new HashMap<String, String>();

        request.putString("headers", new JSONObject(headers).toString());
        request.putString("params", new JSONObject(params).toString());

        request.putString("url", session.getUri());
        request.putString("method", method.name());
        request.putString("uid", requestId);

        try {
            session.parseBody(files);
            // request.putString("body", new JSONObject(files).toString());
            // session.parseBody(new HashMap<String, String>());
            // get the POST body
            String postBody = session.getQueryParameterString();
            // or you can access the POST request's parameters
            Log.d("QVIProtocol", " 1 " + postBody);
            Log.d("QVIProtocol", " 2 " + files.get("postData"));
            request.putString("body", postBody);
            request.putString("data", files.get("postData"));
        } catch (Exception e) {
            Log.d("QVIProtocol", e.toString());
            request.putString("body", "{}");
        }

        return request;
    }

But when i try to fetch to API using below code

const aPromise = await fetch('http://127.0.0.1:5561/ping', {
        method: 'POST',
        headers: {
          token: 'hello-token'
        },
        body: JSON.stringify({ data: '1', hello: '2' })
      })

The response is

body {"body": null, "data": null, "headers": "{\"accept\":\"*\\/*\",\"sec-fetch-site\":\"cross-site\",\"host\":\"127.0.0.1:5561\",\"accept-language\":\"en-US,en;q=0.9\",\"access-control-request-method\":\"POST\",\"origin\":\"https:\\/\\/zrg-team.github.io\",\"sec-fetch-mode\":\"cors\",\"user-agent\":\"Mozilla\\/5.0 (Linux; Android 7.0; small) AppleWebKit\\/537.36 (KHTML, like Gecko) Chrome\\/77.0.3865.116 Mobile Safari\\/537.36\",\"connection\":\"keep-alive\",\"accept-encoding\":\"gzip, deflate, br\",\"http-client-ip\":\"127.0.0.1\",\"access-control-request-headers\":\"token\",\"remote-addr\":\"127.0.0.1\"}", "method": "OPTIONS", "params": "{}", "uid": "1570893737712.75003", "url": "/ping"}
zrg-team commented 4 years ago

any help ?

ruXlab commented 4 years ago

What exactly did you try to archive by creating a map of JSONObjects? I'm asking because you're recreating IHTTPSession in the form of typeless map As per your problem with post body - it seems to me you're sending json, so it needs to be parsed as a json. You can try to read from the session.inputStream and then parse it with anything you like(jackson, Gson, etc). It seems you're trying to use this webserver quite extensively make sure you weighed out other options