0

I'm trying to send data to my server so that I can work with external API. I'm learning now slowly so please forgive for my noobness :) In the code below I converted the elements of an array into a base64 strings (solution). These strings are the ones I would like to send to the server with fetch, however the node server returned UNDEFINED. I suppose I'm wrong in some kind of process (read about async/await etc)... Could someone help me out? Thanks a lot.

NODEJS:

app.post("/upload",upload.any(),(req,res)=>{
console.log(req.files)
res.setHeader("Access-Control-Allow-Origin","*")
res.end("Done.")
});

CLIENT SIDE:
function getBase64(item,index,arr) {
let reader = new FileReader();
reader.readAsDataURL(item);
reader.onload = function(e) {
var rawLog = reader.result; // DataURL - rawLog
var solution = rawLog.split("base64,")[1]; //Rimozione parte prima di base64 
//  console.log(solution);
//  console.log(rawLog);
fetch("http://localhost:3000/upload",{
method:'post',
mode: 'no-cors',

body:solution

}).catch(console.error);
return reader.result;
};}
  
Jack
  • 1
  • 3
  • 2 things: 1st You need to use `app.use(express.urlencoded({ extended: true }))` and `app.use(express.json())` as mention here: https://stackoverflow.com/questions/23259168/what-are-express-json-and-express-urlencoded 2nd The data that you pass in fetch for your POST request will always be stored in `req.body`. You should have a quick glance at documentation of express: https://expressjs.com/en/api.html – Κωνσταντινος Χαφης May 07 '22 at 23:27
  • The files usually are not json but XML.... Do you think it is the same? I mean app.use(espress.json()) will work? – Jack May 09 '22 at 08:06
  • Since anything that is passed through the POST body must always be a JSON in a string format, then what you have to do is: In the client: `body: JSON.stringify({solution})`, And in the server you can access it with: `req.body.solution`. The body above will have this value: `{ solution: "your_xml" }` – Κωνσταντινος Χαφης May 09 '22 at 08:45

1 Answers1

0

When you use mode: 'no-cors' in your request you can't access the API response, you should configure cors in your backend to allow requests from all origins and remove mode: 'no'cors' from your request

https://expressjs.com/en/resources/middleware/cors.html

  • Thanks to your hints I have solved this particular issue of undefined. Keep goint with the rest. Thanks everyone – Jack May 14 '22 at 11:13