Just starting out with AngularJS, running into a problem with ngResource

As a newcomer to AngularJS, I am attempting to create my first app using the reed.co.uk API. Please bear with me as I navigate through this process! :)

Currently, my application is very basic and includes the following:

index.html

<!DOCTYPE html>
<html lang="en" ng-app="reed" class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Reed Start Up App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css" />

    <link rel="stylesheet" href="app.css">
    <script src="bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
    <div class="container">
        <div ng-view></div>
    </div>

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-resource/angular-resource.min.js"></script>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="app.js"></script>
    <script src="components/services/services.js"></script>
    <script src="viewHome/home.js"></script>
</body>
</html>

app.js

'use strict';

// Declare app level module which depends on views, and components
angular.module('reed', ['ngRoute', 'reed.home', 'reedService'])
    .config(['$routeProvider', function($routeProvider){
            $routeProvider.otherwise(
                {
                    redirectTo : '/'
                }
            );
        }]);

home.js

'use strict';

angular.module('reed.home', ['ngRoute', 'reedService'])
    .config(['$routeProvider', function($routeProvider){
        $routeProvider.when(
            '/', {templateUrl : 'viewHome/home.html', controller : 'HomeCtrl'}
        );
    }])
    .controller('HomeCtrl',['$scope', 'Jobs', function($scope, jobs){
        $scope.performSearch = function()
        {
            console.log(
                jobs.query(
                    {
                        keywords : $scope.jobTitle
                    },
                    {
                        method : 'GET',
                        headers : {
                            username : '9f0ebf61-8795-49d7-a1d7-123456789123'
                        }
                    }
                )
            );
        };}
    ]);

home.html

<div class="row">
    <div class="col-sm-12">
        <form role="form">
            <div class="form-group">
                <label form="job-title">
                    Job Title
                </label>
                <input ng-model="jobTitle" id="job-title" placeholder="Please enter your desired job title" class="form-control" type="text" />
            </div>
            <div>
                <button type="submit" class="btn btn-default" ng-click="performSearch()">Submit</button>
            </div>
        </form>
    </div>
</div>

services.js

'use strict';

var jobsServices = angular.module('reedService', ['ngResource']);

jobsServices.factory('Jobs', ['$resource', '$http', function($resource, $http){
        return $resource(
            'http://www.reed.co.uk/api/1.0/search',
            {},
            {
                query : {
                    method : 'GET',
                    headers : {
                        username : '9f0ebf61-8795-49d7-a1d7-123456789123'
                    }
                }
            }
        )
}]);

The documentation for the Reed.co.uk API emphasizes the following:

Important:

You must include your api key in all requests in a basic authentication http header as the username, leaving the password empty.

Despite following these guidelines, I have encountered an issue in my AngularJS app where the request method changes from GET to OPTIONS when setting headers.

If I remove the headers, the request goes through as a GET, but of course, it returns an "Unauthorized request" error from the server.

Any assistance or guidance on how to resolve this would be greatly appreciated!

Answer №1

This question does not specifically relate to Angular. However, a good answer can be found here:

The OPTIONS request that you are seeing is the preflight request. More information about this can be found here:

There are two solutions to resolve this issue (as mentioned above):

  • Respond to the OPTIONS request with the appropriate Access-Control-* headers
  • Consider using a JSONP request instead of plain JSON

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I fetch data from a PHP file using an Ajax request?

Recently, I delved into the realm of Ajax requests and devised this script: function ajax_post(){ // Initiating XMLHttpRequest object var xmlhttp = new XMLHttpRequest(); // Setting up necessary variables for sending to PHP file var url = " ...

Using Font Awesome icons instead of markers in Leaflet

Within this code snippet, I initially utilized data[key].category to represent the corresponding icon as a marker. However, my intention is to switch to Font Awesome icons for a more lightweight runtime experience in instances where multiple icons may ne ...

Can the tooltip of an element be changed while the old tooltip is still visible without having to move the mouse away and then back again?

When I have an HTML anchor element with a tooltip that appears when the mouse is hovered over it, and then I use JavaScript to change the tooltip's text using element.title = "Another Tooltip", the new tooltip text does not immediately update visually ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

A guide to simultaneously sending dual variables by implementing Ajax via JavaScript

I am currently facing an issue with a textarea and PHP variables. I have created a script as shown below: $(document).ready(function(){ $('.post').keyup(function(e){ var post = $.trim($('.post').val()); if (post != ...

Issue with JavaScript cookie not being recognized in server-side code

When I try to access Response.Cookies["alertsCookie"], it returns an empty cookie. To solve this issue, I decided to create two cookies as a workaround. I couldn't figure out how to read a cookie in a specific path, so I stored them in both the page ...

What is the best way to locate the closest points using their positions?

I have a cluster of orbs arranged in the following pattern: https://i.sstatic.net/9FhsQ.png Each orb is evenly spaced from one another. The code I am using for this setup is: geometry = new THREE.SphereGeometry(1.2); material = new THREE.MeshPhongMateri ...

What could be causing the image not to be centered inside the <table><td>?

Currently, I am developing a web application with Google Script that generates a dashboard featuring multiple tables. To design the layout, I am utilizing Bootstrap (https://cdn.jsdelivr.net/npm/[email protected] /dist/css/bootstrap.min.css). Despite ...

What is the best way to retrieve all designs from CouchDB?

I have been working on my application using a combination of CouchDB and Angular technologies. To retrieve all documents, I have implemented the following function: getCommsHistory() { let defer = this.$q.defer(); this.localCommsHistoryDB ...

Tips for efficiently handling navigation re-rendering on a Single Page Application using Vue.js

I am currently in the process of developing a Single Page Application using Vue.js. The structure involves having a template in App.vue which includes a navigation bar followed by a router-view component. When a user attempts to log in, a modal window appe ...

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

Locating a specific item within a mongoDB array

In my collection, I have a mix of strings, objects, and an array containing multiple objects. I'm trying to delete all orders with the object id of ObjectId("587ec66e5ed5cb0061092dbe"). Please refer to the schema and data provided below. I've exh ...

There seems to be an issue with AJAX form submission and it is not functioning properly

Having trouble submitting a form to another page using ajax, as it is not sending the post request. I have included Javascript at the top of the page: <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function(){ ...

I am struggling to create a modal component for a settings button

I am currently working with Quasar VueJS and I have a requirement to add a button on my navbar that will trigger a pop-up dialog settings panel. This settings panel will be used for various functionalities such as dynamic theming, although that is somewhat ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

What is the best way to handle newline characters ( ) when retrieving text files using AJAX?

When using an AJAX call to read a text file, I encountered an issue where it reads the \n\t and backslash symbols. These characters are not needed in the pure text message. How can I ignore or remove them for a clean text display? ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...