0

Given the following code:

fetch(mockproxy+myphp.php,{ 
        method: 'POST',
        headers:{'Token':token["token"]},
        body: name,
    }).then((response) => response.json())
      .then((json)=>{
        toast.success(JSON.stringify(json));
      }) 
      .catch((err) => {
        toast.error(JSON.stringify(err));
       })
  }

mockproxy is helping bypass CORSS. The file looks like this:

const corsAnywhere = require('cors-anywhere');
const express = require('express');
const apicache = require('apicache');
const expressHttpProxy = require('express-http-proxy');
const CORS_PROXY_PORT = 5000;
// Create CORS Anywhere server
corsAnywhere.createServer({}).listen(CORS_PROXY_PORT, () => {
  console.log(
    `Internal CORS Anywhere server started at port ${CORS_PROXY_PORT}`
  );
});
// Create express Cache server
let app = express();
// Register cache middleware for GET and OPTIONS verbs
app.get('/*', cacheMiddleware());
app.options('/*', cacheMiddleware());
// Proxy to CORS server when request misses cache
app.use(expressHttpProxy(`localhost:${CORS_PROXY_PORT}`));
const APP_PORT = process.env.PORT || 5080;
app.listen(APP_PORT, () => {
  console.log(`External CORS cache server started at port ${APP_PORT}`);
});
/**
 * Construct the caching middleware
 */
function cacheMiddleware() {
  const cacheOptions = {
    statusCodes: { include: [200] },
    defaultDuration: 60000,
    appendKey: (req, res) => req.method
  };
  let cacheMiddleware = apicache.options(cacheOptions).middleware();
  return cacheMiddleware;
}

And the server is a shared server where I upload the PHP files so they can access to the DB. The php receives the data and give a response when I use postman but not when I execute the fetch from the dev website, I'm using react, I think it doesn't matter in this case.

The PHP file:

<?php
$headers = apache_request_headers();

header("Access-Control-Allow-Origin: *, ");
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

if ($method == "OPTIONS") {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
    header("HTTP/1.1 200 OK");
    exit;
}

if (isset($_POST["name"])) {
    echo json_encode(" name" . $_POST["name"]); //returned on postman
}else{
    echo json_encode("no name"); //returned on development.
}
exit;
Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
Germán
  • 1,007
  • 1
  • 7
  • 20
  • `body: name,` - What does `name` actually contain? Also, have you checked the console in your browser for errors? – M. Eriksson May 09 '22 at 07:57
  • name contains a dummy object as follows: `const name = {a:"a",b:{c:"c",d:"d"}};` There is no specific error in console for this matter. I have tried many different values but no luck so far, postman succeeds always but my dev environment fails always. Edit: I'm testing it this ways since I have arrays inside an array to send to php. Using formdata + urlSearchParams seems the way but I don't think it is the best way to transform key-value arrays inside arrays. – Germán May 09 '22 at 08:01
  • This probably sends as JSON to begin with, so you won't be able to access any of the data via $_POST. You need to either modify your JS request to send this as `application/x-www-form-urlencoded`, or in PHP receive the data this way, [Receive JSON POST with PHP](https://stackoverflow.com/q/18866571/1427878) – CBroe May 09 '22 at 08:53

1 Answers1

0

So this is a code i use when i want to fetch all data from a form. You can obviously not loop through all forms like i do below but just your single form.

// Query all forms in the DOM or a specific one if you want
const forms = document.querySelectorAll('form');

// Loop through them
forms.forEach((form) => {
    // if method is post
    if (form.method === 'post') {
        form.addEventListener('submit', (event) => {
            // prevent default submit
            event.preventDefault();
            // prepare the data
            let data = new FormData(form);
            // fetch using the form's
            fetch(form.action, {
                method: 'post',
                body: data,
            })
            // get the text() from the Response object
            .then(response => response.text())
            .then(text => {
                // Display it in the result div
                document.getElementById('result').innerHTML = text;
            })
        }, false);
    // if not post (get really)
    } else {
        form.addEventListener('submit', (event) => {
            // prevent default submit
            event.preventDefault();
            // build the URL query params from the submitted data
            const data = new URLSearchParams(new FormData(form).entries());
            // Fetch, URL is formed from the action, append ? and then the query params
            fetch(form.action + '?' + data)
            // get the text() from the Response object
            .then(response => response.text())
            .then(text => {
                // Display it in the result div
                document.getElementById('result').innerHTML = text;
            })
        }, false);
    }
});
Djongov
  • 195
  • 2
  • 13
  • It now returns: `SyntaxError: Unexpected token s in JSON at position 0.` From Postman it returns: `string(73) "name=%7Ba%3A%22a%22%2Cb%3A%7Bc%3A%22c%22%2Cd%3A%22d%22%7D%7D%0A"` – Germán May 09 '22 at 09:14
  • what is the setting for Body on your postman? raw/form-data/x-www-urlencoded? – Djongov May 09 '22 at 09:17
  • It is x-www-form-urlencoded. How do I set the fetch to send in this format? I wonder if it is appropriated for sending key-value arrays inside an array. My form is a bit complex, as the user can create new inputs. – Germán May 09 '22 at 09:22
  • maybe your best bet is to catch all form data from the form if users can create inputs on their own. I have a little code that i use when i want to catpure all form data in a fetch – Djongov May 09 '22 at 09:25
  • Mind to share it, please? – Germán May 09 '22 at 09:28
  • just edited my answer. You can see how i get all form data there and use fetch to send it. You can just use this bit – Djongov May 09 '22 at 09:36
  • I appreciate your time and help, I truly do, however, I find this option overdone for what I'm trying to accomplish. I'll try to find something else, if not I'll use this one. – Germán May 09 '22 at 12:22