Bad Request Error with POST method but not GET method, why?

Hi all,

I’m working on creating a web API at my work place.
I’ve created a nodeJS web API - a compatible driver to use with MariaDB database.
Once the NodeJs Server.Js was ready, my first attempt was to run on a localhost using Postman.
using this URL: localhost:8000/user/register?id=2222 and call was successful
(both for Post and Get since the methods are doing the same thing for the sake of testing).

This maybe a Proxy issue - this is a work pc and I use VPN, in that case, shouldn’t the bad request error also appear for the Get call?

These are the methods as they appear in the Server.JS:

router.get('/register', async function(req, res){
    try{
        const {id} = req.query;
        const sqlQuery = 'INSERT INTO TestTable (id) VALUES (?)';
        const rows = await pool.query(sqlQuery, [id]);
        console.log(rows);
        res.status(200).json(rows);
    } catch(error){
        res.status(400).send(error.message)
    }
})

router.post('/register', async function(req,res){
    try{
        const {id} = req.query;
        const sqlQuery = 'INSERT INTO TestTable (id) VALUES (?)';
        const rows = await pool.query(sqlQuery, [id]);
        console.log(rows);
        res.status(200).json(rows);
    } catch(error){
        res.status(400).send(error.message)
    }
})

Back to Unity I tried both Post and Get methods

Only the Get method is successful, and the new data was added to the table.
The Post method returns Bad Request

This is the Post method in the testing script, C#:

           private IEnumerator PostTest() {
            var formData = new List<IMultipartFormSection>();
            formData.Add(new MultipartFormDataSection("id=1111"));

            // Also tried wwwform and got same result.
            //var formData = new WWWForm();
            //formData.AddField("id", "111");
        
            var request = UnityWebRequest.Post("http://localhost:8000/user/register?", formData);
            request.SetRequestHeader("APIKey", "<api=key>");
            yield return request.SendWebRequest();
            Debug.Log("Status Code: " + request.responseCode);

            if (request.isHttpError || request.isNetworkError) {
                Debug.Log("request resulted in error: " + request.error);
            }
            if (request.downloadHandler.isDone) {
                Debug.Log(request.downloadProgress);
            }
        }

Thanks!

You’ll need to dive deep into this error, doesnt look like a Unity problem.
The fact it returns a 400 - Bad Request is simply because of the try/catch error handling.
Whats the exception and the message in the node.js (the catch(error)) ?
Check if it does help: node.js - how to print the data from post request on console - Stack Overflow

You gotta debug the whole request, find a way to print it and see what does differ from get/post.

2 Likes

Hey @gamedev1506 thanks for the tip to go back into node.js for testing.

I’ve debugged the calling of unitywebrequest.post, and it says in vs code where the node.js app is:
post didn’t work Parameter at position 1 is undefined
INSERT INTO TestTable (id) VALUES (?) - parameters:[undefined]
sql: INSERT INTO TestTable (id) VALUES (?) - parameters:[undefined]

The connection string should be (for local connection):
http://localhost:8000/user/register?id=

I debugged request.url, and the result is: http://localhost:8000/user/register?

  • no id parameter.

I passed this url: http://localhost:8000/user/register?id=3232 into:

var request = UnityWebRequest.Post("http://localhost:8000/user/register?id=3232", null);

and the post method worked.

Why documentation, here: https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, suggest this approach:

var formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("id=44"));

if this approach ignores the passed “formData”?

Was my implementation incorrect?

Thanks!

Ok, what i meant is to actually debug the whole packet.
I was able to debug using this site: https://ptsv2.com/

Using your code i get as multipart values: name=“”, value=“id=1111”.

So i simply changed the code to: formData.Add(new MultipartFormDataSection(name:“id”, data:“1111”));

Now i can see in the dump: name=“id”, value=“1111”.

Give it a try, keep in mind “multipart/form-data” is different from “application/x-www-form-urlencoded”.

Check for example code on both: Unity - Scripting API: Networking.UnityWebRequest.Post

2 Likes

Thanks for the useful link and unity documentation.
So separate the “key” from the “value”, by comma.

This is still not working for me:

var formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("id", "131312"));

This is the url of the post request: http://localhost:8000/user/register?

it ignores the formData variable, and I don’t know why.

My solution to use the Get method to add data to the database.
Its not ideal context wise, but it’s working