Using AJAX with JavaScript to make a Django API request from an external website

This is my first time using the Django Framework. The service provider I am working with requires an active Cookie to access data on their API Docs.

We recently obtained an API Token that we need to use to fetch the data from the framework.

Despite trying to make the data call with the Token through AJAX, I keep getting the same error message "401 (Unauthorized)" in the console.

$.ajax({
    type: 'POST',
    headers: {
        'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
        'Content-Type': 'application/json'
    },
    url: 'www.service-provider.url/api/...',
    
    success: function () {
        console.log("ok");
    },
    error: function () {
        console.log("error");
    }
});

I'm still very new at this and not sure where to even begin. I've looked online for solutions but haven't found anything that solves the issue.

Answer №1

Got it! Always remember to include "Token ..." before the token api key.

 $.ajax({
        type: 'GET',
        url: 'https://my-url.com/api/1.0/?format=json',
        
        headers:{
              "Content-Type": 'application/json',
              "Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
              
        },
        
        success: function(data){
            console.log(data);
        }
    
    });

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

JavaScript code does not contain a defined Nested Loop

My matrix result has encountered an issue of being undefined. The error message displayed in my chrome console at line 25 is: "Cannot set property "0" of undefined." After researching similar problems, I've noticed that most solutions for matrix mult ...

Having trouble inserting data into a database with Ajax and PHP using MySQL?

Seeking guidance on PHP and MySQL for a specific task. I need assistance with storing a user's email and selected language in a database upon button click. My approach involves using Ajax to pass the data to a separate Ajax file (ajax.php) which th ...

Developing Objects for Django Models and Storing in MYSQL

I recently created a sample registration form and managed to successfully save entries to the database. However, I encountered an issue where creating a second entry would override the first one. register.html <form action="/register_process/" method= ...

Navigate back to the previous page following the completion of an AJAX data submission

When using ajax to send data from page A to the server, the spring controller returns welcome page B. This process works correctly on Firefox and Internet Explorer, but on Chrome, there is an issue where after successfully sending the data via ajax, the de ...

Exploring the perfect alignment of buttons with django-bootstrap5

I am trying to position a button next to a form instead of below it: Here is the current layout: https://i.sstatic.net/1jXsy.png And this is how I want it to look: https://i.sstatic.net/nkX9J.png Here is the corresponding code: Form: cla ...

Adding fresh information to the conclusion of a JSON file using PHP

I have a predefined JSON and I am looking to append new data as an element of the existing JSON. I want to add the new data at the end of the JSON as a new element. $jsonData = array(); if (!empty($json_mainQuot)) { $jsonData['mainQuot'] = $js ...

Encountering an unknown symbol '''' while trying to import a JSX file into a JavaScript file in a React application

Looking for some help with my JSX file, here's a snippet: Selector.jsx import React, { Component } from 'react'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel&a ...

A guide on adding a JSON object to an array in R

I have attempted various methods to insert a JSON object into an array and save it in the same format as the example below, but unfortunately, I have not been successful. Does anyone have a solution to accomplish this in R? Thank you EDIT : I have foun ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

Obtain the language of a Wordpress page using javascript

Is there a way to determine the language of a Wordpress page using Javascript? I have discovered a method to detect Spanish: if(window.location.href.indexOf("/es/") > -1) { However, if the website does not use Permalink Settings with "Post name", th ...

Unresponsive Vanilla Bootstrap Navbar Links

I recently started working with the vanilla version of Bootstrap to create a universal template for a friend's websites. Although I have previous experience with Bootstrap and have never encountered any issues, I am now facing a problem. I want to cla ...

Executing a function on a page loaded with AJAX?

I am facing a challenge in running a function when loading an ajax page. In index.html, I am loading page1.html, which contains a function that I want to execute upon page load. I have attempted various solutions without success. Let's say I simply ...

The identifier variable fails to function as a reference when I attempt to utilize it

var lightcount = 0; $("#addlight").click(function(){ var domElement = $('<div id="L' + lightcount +'" class="col-md-3 col-sm-6 text-center"><div class="rumbox"></div><button id="onoff" type="button" c ...

Determining the specified number of rounds in a tournament based on certain conditions utilizing object-oriented programming in Python

Wondering how to properly structure my Django calculator for Swiss-style tournaments. Different tournaments may have varying numbers of rounds, so I need to be able to access scores for each round within the tournament. Below is the model for a single part ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

Enhance your Angular experience by adding two new columns to your JSONArray table

I am faced with a JSON-Array dilemma. Array(8) 0: (3) ["Test", "1", "222"] 1: (3) ["Test", "2", "333"] 2: (3) ["Test", "3", "444"] 3: (3) ["Test", "4", "555"] 4: (3) ["Test", "5", "666"] 5: (3) ["Test", "6", "777"] 6: (3) ["Test", "7", "888"] I want to t ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

How to dynamically disable a dropdown based on the selection of another dropdown using AngularJS

This project has been more challenging than I anticipated. I thought it would be a simple task to accomplish. Currently, I am developing a basic form with an input text field and two dropdown boxes. These dropdown boxes represent different types of contra ...

Utilizing Angular.JS to sort items based on the chosen option in a select dropdown menu

I am utilizing the WP API to display a list of posts on a page from a JSON file. I have successfully implemented filtering through an input field named searchrecipe, which allows me to search for post titles. However, I am facing a challenge with filterin ...

Experiencing difficulty with rendering a Chartist graph in an HTML page when a button is clicked

I encountered an issue while attempting to display the Chartist graph when the user clicks the button. Normally, the graph displays properly but when I try using ajax show(), the graph shrinks as shown in the image below: Without button clicked https://i. ...