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);
}
}