Using the after ship.com API with CORS in JavaScript using Ajax

Hi everyone, this is my first time posting here.

I'm having trouble sending data via the POST method.

When I checked the console, I saw the following error message: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I've done some research on CORS, but the issue persists.

Below is the code I'm working with:

function track() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://api.aftership.com/v4/trackings/', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('aftership-api-key', 'key');

    xhr.onload = function() {
        if(xhr.status === 200) {
            console.log('Does it work? : ' + xhr.responseText);
        }
        else {
            console.log('IT DOESN'T WORK!' + xhr.status);
        }
    }
    xhr.send("tracking_number=number");
    //xhr.send();
}

At times, I've managed to create a tracking number using the GET method, but it's not a sustainable solution. However, I can use the DELETE method with a CORS plugin in Google Chrome after creating the tracking number. Without the plugin, the DELETE method doesn't work.

I'm interested in developing my own application on phonegap using the Aftership API.

I would greatly appreciate any help or advice! :D

Answer №1

If you're facing issues with your website's content security policy, consider making changes to the meta tag in your HTML file. Here is the original meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">
You can modify it to allow any traffic by changing the default-src to * like this:
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">
By including the * in default-src, it permits all traffic, but you can specify your own URL for added security. If necessary, you could remove the meta tag entirely, although this is not recommended as it may pose security risks. It is advisable to only do this temporarily to troubleshoot the issue. For more information on Content Security Policy, refer to the following link:

If the issue persists, it may be related to whitelisting problems which can be explained further or explored through the provided link.

Answer №2

Added meta tag and whitelist plugin to the configuration file

In the config.xml file, the following lines were added:

<access origin="*" />
<allow-intent href="http://*/" />
<allow-intent href="https://*/*" />

Despite the modifications, the POST method still does not work...

Perhaps it would be easier to implement the POST method using PHP or node.js?

I must solve this issue in order to complete my app :(

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

Creating custom result formats through WCF to return JSONP

So, I have a WCF service that gives back a customized object with specific properties that I need to utilize. [DataContract] public class CommonJsonResponse { [DataMember] public object Data { get; set; } [DataMember] public bool Success ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

Explaining the implementation of JQuery's onload event and its impact on reducing dependencies

Contained within a table is some data https://i.stack.imgur.com/gQyJQ.png Upon clicking the edit button, I am able to modify the information in that specific row. The Menu Category and Menu are populated through Dependent dropdowns. https://i.stack.imgur ...

Having issues with a partial view not loading properly when making an ajax call in MVC5

Currently, I am developing a view that serves as a create view for customers. Within the "Create" View, I have implemented a textbox to search for items in the database and then display their details on a partial view. The partial view action is successfu ...

Looping through a sequence of asynchronous tasks, utilizing the async/await syntax, writing data to

I'm currently working on a script to download pdf files from a specified URL and save them to my local disk. However, I have encountered an issue where I need each file to be downloaded one at a time with a one-second delay in between (to ensure that ...

Tips on showcasing array elements within a table's tbody section and including several values within the same array

I am struggling to figure out how to display array values in my table rows that I receive from input values. I have created an array, but I can't seem to find a way to display them in the table. Furthermore, I want to be able to add more values to th ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...

Is it possible to direct the user to a particular link upon swiping to unlock?

Hello everyone, I could use some assistance with this code. I am looking to redirect someone to a specific page when they swipe to unlock and automatically transfer them to another page when the swipe ends. Any help is greatly appreciated. Thank you! $ ...

Response in JSON format in Django

Seeking assistance with creating an Ajax method to load content on my website: Below is the method I am using: def receive_subcategory(request, id): subcategories = SubCategory.objects.filter(main_category=id) return HttpResponse(subcategories) And here ...

What is the purpose of being able to include additional scripts within package.json files?

I am attempting to include a new script in the package.json file under the scripts section. For instance, I have the following: { "scripts": { "delete": "rm -f wwwroot/*.js wwwroot/*.css wwwroot/*.html wwwroot/*.map" "watch": "npm run delete; parc ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

Triggering updates from multiple controls in a GridView using ASP.NET

I am faced with a challenge involving a gridview containing numerous checkboxes, sometimes over 40. My goal is to have these checkboxes trigger a .NET function in the code behind upon being clicked. The complication arises from the fact that the checkboxes ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Troubleshooting issue: Bootstrap button onclick function not firing

My node express app is using EJS for templating. Within the app, there is a button: <button type="button" class="btn btn-success" onclick="exportWithObjectId('<%= user.id %>')">Export to csv</button> Accompanying the button i ...

Filter an array of objects recursively based on various properties

I need help filtering an object with nested arrays based on specific criteria. Specifically, I want to filter the main array by matching either RazaoSocial:"AAS" or Produtos:[{Descricao:"AAS"}] This is my code: var input = [ { RazaoSocial: 'AA ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...

Could this be considered a typical trend - opting to return data instead of a promise?

I recently came across a new approach while reading 'Mean Machine'. Typically, I have always been taught to return a promise from a service to the controller and then handle it using .success or .then. In this case, the author is directly retur ...

Pausing until the user clicks the button again

I have implemented two buttons on this page - one with a class of 'arrow-up' and the other with a class of 'arrow-down'. Clicking on the 'arrow-down' button will smoothly scroll down to the next section, while clicking on the ...

Adjust the styling of the anchor tag within the selected div by utilizing jQuery

I am struggling with changing the color of a specific anchor tag when clicked inside a div with class .product_wishlist. Currently, all anchor tags within .pw div are changing colors. Is there a way to apply selected css only to the clicked element? Any he ...