I
I
ivan_ivanov_ivanych2021-03-26 04:14:14
Node.js
ivan_ivanov_ivanych, 2021-03-26 04:14:14

Why can't connect to node.js server?

Good afternoon!
I am writing a React/redux application using a postrgess heroku database - a block with comments.
For some reason React is not connecting to my server in node. With a get request, it simply returns the html text

file server.js, from which the application is launched

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

const port = process.env.PORT || 8080;
const merchant_model = require('./merchant_model')

const app = express();

app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.json())
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers');
  next();
});

app.get('/', function (req, res) {
  merchant_model.getMerchants()
   .then(responce => {
     res.status(200).send(responce)
     console.log(responce);
   })
   .catch(err => {
     res.status(500).send(err)
   })
});


merchant_model.js
const { Client } = require('pg');
require('dotenv').config();


const client = new Client({
    connectionString: process.env.DATABASE_URL,
    ssl: {
      rejectUnauthorized: false
    }
});

const getMerchants = () => {
  return new Promise(function(resolve, reject) {
    client.query('SELECT * FROM comments_table', (error, results) => {
      if (error) {
        reject(error)
      }
      resolve(results.rows);
    })
  }) 
}


A piece of code with a get request in React (then the result should fall into the global state)
fetch('http://localhost:8080/')
  .then(responce => {
    return responce.text();
  })
  .then(data => {
    console.log(data);  //Выдает html-код в виде обычного текста
  })

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question