Error when trying to parse the response body

I have an endpoint, that by design is returning text/html formatted code.
I have my test in postman setup with the requisite Accept */* and when I make the call, I am getting the properly formatted html file.
However postman, while receiving a 200 success message is issuing a:

error. Have no idea why. Making this same call in any browser or curl shows no such problem.
What’s Postman’s problem with this?

Is there a test or a script that you have in place that is using pm.response.json() or JSON.parse(responseBody)?

1 Like

A script where exactly? My postman call is just a get instruction.

I don’t know anything about the request or the collection you have but i suspect something is in there. :joy:

It looks like something is trying to parse the response as JSON when it’s a HTML response.

Can you provide images of the app so we can see what you’re doing?

2 Likes

Hey Danny… sorry to have wasted your time. Turns out someone hadn’t updated tests for this endpoint that was totally changed in content… this was the result of deprecated test condition.

Never wasting anyone’s time :grin:

Glad to see you found the issue. :trophy:

2 Likes

Hey Danny,
i’m facing the same issue. Even, I remove all the scripts that i have in the Test, i’m still seeing this error There was an error in evaluating the test script: JSONError: Unexpected token '%' at 1:1 %PDF-1.3 ^ Just noted, the response is not json content. it’s pdf file.

Yes. Danny you’re right. there were doing in the script. pm.response.json(): all sorted.

Thanks Danny, the code i typed in the test was what caused it. Thanks

Hey Danny,
i’m facing the same issue. Even, I remove all the scripts that i have in the Test, i’m still seeing this error There was an error in evaluating the test script: JSONError: Unexpected token '%' at 1:1 %PDF-1.3 ^ .

Could it be a typo in your code?

response.data[0] instead of responsex.data[0]

Also, the tests["name"] style of writing Postman tests is deprecated.

1 Like

Hi @danny-dainton Can you please help me in that.?
Appreciate your time.
Thanks.

The response isn’t JSON so that’s why you’re seeing an error.

You can capture that string value with this:

let response = pm.response.text()
1 Like

Thanks you for quick response you save my time.

updated my schema due to outdated version in postman. It’s resolved.

Hello! I am currently also facing the same issue, and I have pm.response.json() in my code. May I know what I should be using instead? Would appreciate it if you could dumb it down a bit for me as I am new to coding…

Thanks!

For anyone else that is struggling with this issue, I was able to resolve it by removing an extra slash on my base_url variable. I was using an environment variable like this:

{{base_url}}/my/endpoints

However, when I copy and pasted the base_url value, it was ending with a slash like this:

https://api.mysite.com/

As you can imagine, the way Postman then interpreted this was

https://api.mysite.com//my/endpoint

Which is invalid.

When I change it to https://api.mysite.com everything worked as expected. Had nothing to do with what was in the Test section of my Post endpoint.

Hi everybody I’m having the error:“There was an error in evaluating the test script: JSONError: Unexpected token ‘T’ at 1:1 The resource you are looking for has been removed, had its name changed, or is ^”
and my test code is: var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable(“secondToken”,(jsonData.results[0].token));

This usually means that the responseBody that you are receiving is not valid JSON, so when the JSON.parse(responseBody) is called it cannot parse the invalid JSON string.

I’m having a super-confusing issue. I am having this same “Unexpected token” issue, so logging the response to the console shows that it’s already a json! Turns out that it’s a response from a GET request, not my POST request.

My pre-request script is apparently redirecting to a GET request using just the base URL. I do not know why it’s redirecting, as I cannot find any code in the endpoint in question that explicitly redirects.

I’ve tried turning off the “Automatically follow redirects” setting for any calls that use this pre-request script, as well as enabling the “Follow original HTTP Method” setting when that didn’t work. Both were recommended in this Postman article, but neither fixes the issue, probably because the problem is in a pre-request script, not the main request itself.

Here’s the script:

const postRequest = {
    url: `${pm.environment.get('url')}/auth/login`,
    method: "POST",
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
    },
    body: {
        mode: "urlencoded",
        urlencoded: [
            {key: "email", value: pm.environment.get("loginUserEmail"), disabled: false},
            {key: "password", value: pm.environment.get("loginUserPass"), disabled: false}
        ]        
    }
};
  
const getToken = true;
  
if (!pm.environment.get("currentAccessToken")) {
    console.log("Token missing");
} else {
    getToken = false;
    console.log("Token good");
}
  
if (getToken) {
    pm.sendRequest(postRequest, function (err, res) {
        console.log("error: ", err);
        console.log("result: ", res);
        if (err === null) {
            console.log("Saving the token");
            const responseJson = res.json();
            console.log(responseJson);
            pm.environment.set("currentAccessToken", responseJson.access_token);
        }
    });
}

And the result in the console:

If I call that /auth/login endpoint from a separate Postman call, it returns the correct JSON with access_token. So why would the pre-request script be different?

For reference, here’s the endpoint:

class LoginController extends Controller
{
    public function __invoke(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        $device = substr($request->userAgent() ?? '', 0, 255);
        $expiresAt = $request->remember ? null : now()->addMinutes(config('session.lifetime'));

        return response()->json([
            'access_token' => $user->createToken($device, expiresAt: $expiresAt)->plainTextToken,
        ], Response::HTTP_CREATED);
    }
}