Send array from node.js and use client side

Viewed 789

Im a beginner with node.js so bear with me please :D

Simple task: I use express and I want to send an array, lets say ["item1", "item2"] from a node server to a client that calls the server with a get method. When I tried this, I stumbled upon the CORS error.

I also thought about doing a this through a post:

-client:

     $(document).ready(function () {
        $(".testButton").click(function (e) {
            e.preventDefault();
            $.ajax({
                url: "http://localhost:3000/test_post",
                type: "post",
                data: "sent",
                success: function () {}
            });
     });

-server:

app.post('/Quiz_post', function (req, res) {
  res.send(["item1", "item2"]);
});

But this also doesnt work. Now I am trying to use cross-fetch client side. Could you please guide me a bit? Thanks!

1 Answers

Add this code in ur app.js to enable CORS.

npm i cors in the project 1st

var cors = require('cors');

var app= express(); //After this line of code add the code below

app.use(cors());
Related