简体   繁体   English

如何将前端 ReactJs 项目文件夹与 NodeJs 后端连接?

[英]How to connect Frontend ReactJs Project Folder with NodeJs Backend?

I Have a React web app that has crypto portfolio, Now I want to connect it with Backend server.js.我有一个具有加密组合的 React web 应用程序,现在我想将它与后端 server.js 连接。 The deployed web app should set start from Node Server.部署的 web 应用程序应设置从节点服务器启动。 I am fairly new with NodeJS but Ive tried solutions like cors and all.我对 NodeJS 相当陌生,但我尝试过 cors 等解决方案。

I am Fairely New to node can anyone please help me to connect my React folder to backend node folder.我是节点的新手,任何人都可以帮我将我的 React 文件夹连接到后端节点文件夹。 I'll be very grateful.我将不胜感激。

In react I've made Production Build also but it didn't worked.在反应中,我也进行了生产构建,但没有奏效。

Here's Server.js Code:这是 Server.js 代码:

const express = require('express');
const cors = require('cors');
const path = require('path');

app.use(express.json({ extended: false }));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});
if (process.env.NODE_ENV === 'production') {
  //static folder
  app.use(express.static('client/build'));
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

Now I am Getting the error in server现在我在服务器中收到错误

connot GET /

Github Project Link of frontend: https://github.com/Twelve03/crypto-portfolio Github 前端项目链接: https://github.com/Twelve03/crypto-portfolio

If you are starting the server using the code app.listen(3000);如果您使用代码app.listen(3000); And it's still not working, then you might have to set the environment variable NODE_ENV=production you can do it like this NODE_ENV=production node server.js而且它仍然无法正常工作,那么您可能必须设置环境变量NODE_ENV=production您可以这样做NODE_ENV=production node server.js

Better practice will be to keep all you environment variables inside a .env file and then use the dotenv package to read the environment variables from the .env file更好的做法是将所有环境变量保存在.env文件中,然后使用dotenv package 从.env文件中读取环境变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM