Theetje
Theetje

Reputation: 29

Ajax request header with REST API

I’m trying to do a ajax GET request. The doc say I should add a authorization with key in the header but I don’t really know how to add it. I tried this but it gives an Uncaught SyntaxError: Unexpected identifier in line 16. I think it has to do with adding the header. The api is REST so returns JSON and should be a GET.

my code looks like this:

jQuery(document).ready(function($) {
var postcode = '1000AA';
var houseNumber = '4';
var urlPath = 'https://api.postcode.nl/rest/addresses/postcode/'
+ postcode + '/'
+ houseNumber + '/';
console.log(urlPath);
$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("Authorization","*****************");
    }
    url: urlPath
}).then(function(data) {
    $('.street').append(data.street);
        $('.city').append(data.city);
    });
});

The header should come like this:

GET /rest/addresses/postcode/2012ES/30/ HTTP/1.1 Host: api.postcode.nl Authorization: Basic 2eTpkU******

and the url like https://api.postcode.nl/rest/addresses/postcode/{postcode}/{houseNumber}/{houseNumberAddition}

Upvotes: 1

Views: 1230

Answers (2)

Sandeep
Sandeep

Reputation: 65

The above answer is all you need. Only thing I wanted to add is that I often throw my code into an editor at https://ace.c9.io/, which will point out where your error is, and often what you're doing wrong.

Upvotes: 0

Eyk Rehbein
Eyk Rehbein

Reputation: 3868

$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("Authorization","*****************");
    },
    url: urlPath
}).then(function(data) {
    $('.street').append(data.street);
        $('.city').append(data.city);
    });
});

A comma between the beforesend and url entry were missed. Syntax errors like this aren't triggered by logical issues like a wrong header or something like this. The issue can only be wrong syntax

Upvotes: 1

Related Questions