All Articles
Developer

Debug a Browser API Request: URL Encoding and CORS

December 1, 20264 min read

URL Encoder in Encode mode with Component type; input coffee & tea gives output coffee%20%26%20tea

If an API call works in a command-line tool but fails in the browser, check two different things: whether the query string is encoded correctly, and whether the server allows your page's origin through CORS. The URL Encoder can only help with the first. A CORS error cannot be fixed by changing the URL.

Step 1: encode each value, not the whole URL

  1. Open the URL Encoder, keep Mode on Encode and choose Type: Component.
  2. Type a single value, coffee & tea, in Input (Plain). Output (Encoded) shows coffee%20%26%20tea. The & became %26, so it can no longer split the query.
URL Encoder in Encode mode with Component type; input São Paulo gives output S%C3%A3o%20Paulo
  1. Replace the input with São Paulo. The output is S%C3%A3o%20Paulo: the accented letter becomes two UTF-8 bytes.
  2. Join the pieces yourself, keeping the structural ?, = and & as they are: https://api.example.com/search?q=coffee%20%26%20tea&city=S%C3%A3o%20Paulo

Use Component for values. The Standard type turns spaces into + unless you tick Preserve spaces as %20, which is fine for form-style queries but check what your API expects. Full URL is for tidying a URL, not for values: in testing, a URL that already contained %20 came out as %2520, and a raw & inside a value was treated as a new parameter.

Step 2: read the CORS error separately

Open the browser's developer tools. A CORS failure appears in the Console as a message that the request was blocked by the CORS policy, and the Network tab may show a preflight OPTIONS request first. The browser enforces CORS using headers the server returns, such as Access-Control-Allow-Origin. Command-line tools do not enforce it, which is why the same request can work there. MDN's CORS guide explains the preflight rules.

Advertisement

What not to do

Do not put a secret API key in public browser code to get around a blocked request. Ask the API owner to allow your origin, use their documented browser flow, or send the request from your own server.

If it doesn't work

  • If the server returns 400 or a wrong result, compare your encoded query with the one that worked in the command line, character by character.
  • If the console says the request was blocked by CORS, the URL is not the cause; check the response headers and the method and headers your request sends.
  • If you see %2520, the text was encoded twice. Encode the plain value once.
Advertisement
URL EncoderCORSAPI