The get method is functional, however, the post method is not working as expected in Zap

I'm currently using zapworks studio to create an AR experience. This involves using Z.ajax for ajax calls, including GET and POST requests. For hosting couchdb, I've opted for smileupps due to their free hosting service. The CORS configuration is as follows:

credentials: false; headers:Accept, Authorization, Content-Type, Origin; methods: GET,POST,PUT,DELETE,OPTIONS,HEAD; origins: *

While everything functions smoothly on Windows when launching ZapWorks Studio, the problem arises when trying to make a POST ajax call after scanning the zapcode with an Android device. It seems to be connected to using basic authentication, allowing only admin access. Despite being able to manage the database directly from both desktop and phone browsers, the issue persists.

Various attempts have been made to resolve this, such as removing authentication and adjusting CORS configurations, all to no avail. Although initially thought to be a CORS-related complication, it's peculiar that while things run smoothly on Windows, the POST request consistently fails on mobile devices, displaying status code 0.

UPDATE - Testing on apitester shows successful outcomes both on desktop and mobile versions.

UPDATE - To provide further insight, here's the zpp file demonstrating the logic: ZPP File

UPDATE - Trying the REST Api Client app on my phone also yielded success. This points towards a potential CORS or ZapWorks-related issue as it seamlessly operates on Windows but encounters problems on mobile platforms.

UPDATE - While identifying the root of the problem, resolving it remains puzzling. Setting up a proxy for debugging requests from ZapWorks Studio seemed to shed light on the matter, revealing a preflight request issue resulting in a "HTTP/1.1 405 Method Not Allowed" response despite indicating that POST method should be allowed.

The provided request details reveal the attempt and subsequent feedback:

OPTIONS /ranking HTTP/1.1
Host: somehost.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G950U1 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36
Access-Control-Request-Headers: authorization,content-type,x-requested-with
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US
X-Requested-With: com.zappar.Zappar

The encountered response read as follows:

HTTP/1.1 405 Method Not Allowed
Server: CouchDB/1.6.0 (Erlang OTP/R15B01)
Date: Mon, 18 Jun 2018 21:22:12 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 76
Cache-Control: must-revalidate
Allow: DELETE,GET,HEAD,POST
Access-Control-Expose-Headers: Cache-Control, Content-Type, Server
Access-Control-Allow-Origin: null
Connection: keep-alive

{"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST allowed"}

Intriguingly, although POST permission is clearly stated, the situation remains unresolved...

The absence of a preflight request on the Windows front hints at why the process succeeds there, unlike on mobile devices. The current challenge lies in configuring CORS on couchdb to accommodate Android operations effectively. Available settings include:

enable_cors: true
credentials: false
headers:Accept, Authorization, Content-Type, Origin
methods:GET,POST,PUT,DELETE,OPTIONS,HEAD
origins:*

Provided below is the relevant code snippet:

const Open_SansRegular_ttf0 = symbol.nodes.Open_SansRegular_ttf0;

parent.on("ready", () => {
    const Plane0 = symbol.nodes.Plane0;

    let ajaxParameters : Z.Ajax.Parameters = {
        url: "https://something.smileupps.com/test/_all_docs?include_docs=true",
        headers: {"Authorization": "Basic my64encoding"},
        method: "GET",
        timeout: 3000
    };

    // Executing AJAX request
    Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});

    ajaxParameters = {
        url: "https://something.smileupps.com/test",
        headers: {"Content-Type":"application/json", "Authorization": "Basic my64encoding"},
        method: "POST",
        body: '{"name" : "asdasd", "something": 234}',
        timeout: 3000
    };

    Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});
});

function checkRequest(statusCode, data) {
    if (statusCode === 0) {
        Open_SansRegular_ttf0.text("Unable to connect - check network connection.");
        console.log("Unable to connect - check network connection.");
        return;
    }

    if (statusCode < 200 || statusCode >= 300) {
        Open_SansRegular_ttf0.text("HTTP request failed: " + statusCode);
        console.log("HTTP request failed: " + statusCode);
        return;
    }

    let parsedData;
    try {
        parsedData = JSON.parse(data);
    } catch (e) {
        Open_SansRegular_ttf0.text("Unable to parse JSON: " + e);
        console.log("Unable to parse JSON: " + e);
        return;
    }

    return parsedData;
}

UPDATEResponding to requests under Windows:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US
Authorization:Basic mybase64encoding
Connection:keep-alive
Content-Length:37
Content-Type:application/json
Host:http://something.smileupps.com/test
Origin:file://
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ZapWorksStudio/4.0.4-stable Chrome/58.0.3029.110 Electron/1.7.9 Safari/537.36
X-DevTools-Request-Id:3680.9
X-Requested-With:XMLHttpRequest

and the corresponding response:

Access-Control-Allow-Origin:file://
Access-Control-Expose-Headers:Cache-Control, Content-Type, ETag, Server
Cache-Control:must-revalidate
Content-Length:95
Content-Type:text/plain; charset=utf-8
Date:Mon, 18 Jun 2018 21:36:22 GMT
ETag:"1-512f89feb3d0a88781119e772ec6fd7b"
Location:http://something.smileupps.com/test
Server:CouchDB/1.6.0 (Erlang OTP/R15B01)

No preflight mechanism detected.

Answer №1

It seems like the issue lies within the request itself. The presence of Origin: null typically occurs when the webpage making the xhr request is accessed using the file: protocol instead of http or https. In such cases, successful CORS requests cannot be made.

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

Implementing adaptive window.scrollY listener in React to account for different screen sizes

I am currently using a useEffect hook to create a fade-in effect for text based on scroll position. While this works perfectly on my 27-inch MAC screen, I am facing challenges when viewing it on a smaller screen. I am unsure how to adjust the useEffect to ...

What is the most effective way to retrieve both grouped data and all data from mongodb?

I have successfully retrieved totalAccount and totalBalance using the code snippet above. However, I am facing an issue where no other field or data besides those two are showing up. How can I modify this code to also fetch all the data from my collectio ...

"Explore the capabilities of WebWorks AJAX for seamless cross-domain requests

Currently developing a playbook app using webworks sdk. I am encountering an issue with making an HTTP request (method: post) while sending and receiving data. Although I am able to receive a response from the server, the server does not seem to receive th ...

Using AJAX to dynamically update a DIV when there are changes in the XML data

After dedicating the past four years to solving this problem intermittently, my brain is feeling the strain. I serve as a volunteer designer for a local community project involving a radio station. Our "On Air" module showcases the current and upcoming tr ...

Unable to return true within an ajax call

Currently, I am working on implementing form validation which involves checking if the email address exists to return either true or false. However, the issue I am facing is that it does not return true, hence preventing me from validating other fields aut ...

Issue with request body in Express Js: no data provided

After updating the modules to their latest versions, I am unable to receive any GET or POST variables. I am using NODE v0.12.2. What could be causing this issue? var express = require("express"); var bodyParser = require("body-p ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

Monitoring the libraries and scripts utilized by a website

Whenever I upload my STL files onto the platform known as Thingiverse.com, it automatically generates a preview of my 3D design files. My curiosity lies in discovering which specific libraries this website employs for this purpose. For example, when I exam ...

Typo3's Paginate Widget causes layout issues when loaded dynamically via ajax

Currently, I am encountering an issue while using the pagination widget in conjunction with ajax. My approach involves selecting a category and then sending an ajax request to retrieve the corresponding list by loading the data into the template and return ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Challenge with implementing custom http headers in jQuery's $.ajax请求

I need help with querying a REST webservice that requires custom http headers for authentication. When I make a POST request without the headers, I get the expected error. However, when I include the headers, I receive a 404 error instead of the desired r ...

Adjust the attributes of THREE.tubeGeometry

Within my Three.js scene, I currently have a tube object that I need to dynamically adjust the start and end points of. I believe this approach is more efficient than creating a new tube with updated points and removing the old one. If this is not the case ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Creating a dedicated subfolder for 4 REST API routes for better organization

I'm struggling to figure out why my .get('/:post_id') route isn't working... My project's folder structure looks like this: app.js routes --api ----blog.js The blog.js file is located in the routes/api folder. In app.js, I&apo ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

Create a sequence of reactions using Selenium WebDriver

I am looking to gather a set of responses while browsing a website, and then "recreate" the process using those responses. Upon exploring an different discussion, I stumbled upon this method for rendering HTML: content = requests.get("https://stackoverfl ...

Is it possible to "preload" an image using JavaScript in order to utilize it as a CSS background-image?

Is it possible to pre-load images into a web page using Javascript in order to use them as CSS background images without experiencing any delay due to requests or uploads? If it is possible, how can this be achieved? ...

`The date field within the JSON cannot be verified.`

I am facing an issue. I have a json file with a date in this format: "2017-05-15T19:30:00+01:00". I want to validate the date from the server using SimpleDateFormat, and I am using the format: "yyyy-MM-dd'T'HH:mm:ssZ". When I parse the expected ...

Locating function definitions in etags using Emacs

I find syntax check in js2-mode to be quite effective. However, there are times when I wish to name a function "delete" or "new" even though it may not be the best practice. Js2-mode often flags this as an error. Is there a way to use built-in keywords as ...