Search code examples
erlanghttphandlercowboyerl

How to use post and get handlers in erlang-cowboy


Please help me as iam creating a new project i.e..,creating a login page using erlang-cowboy login page contains username,password and submit button when user enters the data and clicks the submit button in browser the details of the user should save in server for that i created a file toppage_handler.erl but when iam entering the make command errors are raising

errors:

root@ErlangCowboy:~/cowboy/examples/practice_world# make
make[1]: Entering directory `/root/cowboy/examples/practice_world/deps/cowboy'
make[2]: Entering directory `/root/cowboy/examples/practice_world/deps/cowlib'
 APP    cowlib.app.src
make[2]: Leaving directory `/root/cowboy/examples/practice_world/deps/cowlib'
make[2]: Entering directory `/root/cowboy/examples/practice_world/deps/ranch'
 APP    ranch.app.src
make[2]: Leaving directory `/root/cowboy/examples/practice_world/deps/ranch'
 APP    cowboy.app.src
make[1]: Leaving directory `/root/cowboy/examples/practice_world/deps/cowboy'
 ERLC   practice_world_app.erl practice_world_sup.erl toppage_handler.erl
src/toppage_handler.erl:14: syntax error before: '{'
src/toppage_handler.erl:4: function handle/2 undefined
make: *** [ebin/practice_world.app] Error 1

and the toppage_handler.erl file is:

-module(toppage_handler).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
    {ok, Req, undefined}.

handle(Req, State) ->
    {Method, Req2} = cowboy_req:method(Req),
    case Method of
        <<"POST">> ->
            Body = <<"<h1>This is a response for POST</h1>">>
            {ok, Req3} = cowboy_req:reply(200, [], Body, Req3),
            {ok, Req3, State};
        <<"GET">> ->
            Body = <<"<h1>This is a response for GET</h1>">>
            {ok, Req3} = cowboy_req:reply(200, [], Body, Req3),
            {ok, Req3, State};
        _ ->
            Body = <<"<h1>This is a response for other methods</h1>">>
            {ok, Req3} = cowboy_req:reply(200, [], Body, Req3),
            {ok, Req3, State}
    end.

terminate(_Reason, _Req, _State) ->
    ok.

Solution

  • The error message is indicating that your {ok, Req3} = ... line has a syntax error prior to {. Since { is the first important character on the line, we can reasonably assume that the error is actually on the line before it.

    Indeed, the error stems from this line:

    Body = <<"<h1>This is a response for POST</h1>">>
    

    And is actually repeated in both other case clauses. In the first line of each of your case clauses, you're missing the expression terminator, ,. The lines should be:

    Body = <<"<h1>This is a response for POST</h1>">>,
    {ok, Req3} = ...