A
A
AlexNoch2020-10-29 03:24:15
Node.js
AlexNoch, 2020-10-29 03:24:15

How to make friends React and Backend part on Node.js?

I just started developing applications, I can't figure it out. How to connect frontend - on React and server on Node.js?
Remotely - I bought a VPS, set it up, uploaded node.js , launched it. I opened my React application from the browser, sent an AJAX request, and I received a response from my server. OK. How can I develop everything locally? I have run npm node app.js application on port 8000. I start my react app with npm start, it opens on port 3000. But Ajax requests don't get any response. I tried setting the headers "Content-Type": "application/json",
"Access-Control-Allow-Origin":"*" , on the remote server it gave the result. Locally, it didn't. How to develop locally?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Yuriev, 2020-10-29
@AlexNoch

How much I (dis)like these questions about node.js and ports.
Install nginx on a localhost that correctly routes requests from port 80 to port 3000 or 8000, depending on the request, and enjoy yourself.
How right? Yes, just like you set up the VPS.

R
Robur, 2020-10-29
@Robur

But Ajax requests don't get any response.

there is no such error "no response"
Either the request goes to the wrong place, or the server does not start.
there is no difficulty here at all - turn on the cors node on the server, and start the react and the server on any ports you like.
The fact that something is not working for you means that you just did something wrong.
check that the server is running and available on port 3000 to begin with, at least curl or postman, or just open this url in a browser.

A
AlexNoch, 2020-10-31
@AlexNoch

Drumroll, Solution!

http.createServer((req,res)=>{
    res.writeHead(200, {
        "Access-Control-Allow-Origin":"*",
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials":"true"
        });
    res.end(JSON.stringify({newName:"Hello World"}))
}).listen(3001);

The whole point was that the header was sent incorrectly, due to single quotes, and colons : Be careful)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question