0

I get errors:

localhost/:1 Failed to load http://localhost:5000/api/hello: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is my asynchronously POST:

async function submitToServer(data){

  try{
      let response = await fetch('http://localhost:5000/api/hello', {
          method: 'POST',
          headers: {
            'Content-type' :  'application/json',
          },
          body: JSON.stringify(data),
        });
        let responseJson = await response.json();
        return responseJson;
  }   catch (error) {
          console.error(error);
  }
}

And this is my server:

const express = require('express');

const app = express();
const port = process.env.PORT || 5000;

app.get('/api/hello', (req, res) => {
  res.send({ express: 'Hello From Express' });
});

app.listen(port, () => console.log(`Listening on port ${port}`));

What should I do to send this information to the API?
Do I need to create an endpoint or something?

So I installed cors npm.
Now I have these errors:

POST localhost:5000/api/hello 404 (Not Found)

and

SyntaxError: Unexpected token < in JSON at position 0

What can I do now?

2

1 Answer 1

2

You are not returning JSON from your express server.

res.send({ express: 'Hello From Express' });

should be

res.json({ express: 'Hello From Express' });

Also, you defined the route for GET, yet you sending a POST request. So your handler should be:

app.post('/api/hello', (req, res) => {
  res.json({ express: 'Hello From Express' });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Still. StepOneValidationForm.js:42 SyntaxError: Unexpected token < in JSON at position 0
Ok how now i can display this data?
Ask a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.