skip to Main Content

This is my first time using cors and node.js, I am trying to call a Web API hosted on one URL from another URL.

I cannot even get cors to work simple app.use(cors());

I tried more complex configurations with origins and whatnot, still no luck.

The api lives on https://api.example.app and is being called from https://myapp.example.app

I am getting all kinds of cors errors.

Note, I am also using CloudFlare and Nginx Proxy Manager

Also, I CAN go to the https://api.example.app/select and get back my data that way without issue. But thats the only scenario working.

var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var app = express();
var port = 3333;

app.use(express.text());

app.use(cors());

var pool = mysql.createPool({
    connectionLimit: 10,
    host: '192.168.1.200',
    port: 3306,
    user: 'user',
    password: 'password',
    database: 'mydb'
});

app.get('/select', (req, res) => {
    pool.query('SELECT * FROM mytable', (error, results, fields) => {
        if (error) {
            console.error('Error retrieving data:', error);
            return res.status(500).send('Failed to retrieve data from database');
        }
        console.log('Data retrieved successfully:', results);
        res.status(200).json(results);
    });
});

app.post('/insert', (req, res) => {
    var string = req.body;

    console.log(req.body);

    if (!string) {
        return res.status(400).send('String is required');
    }

    pool.query('INSERT INTO mytable(user) VALUES (?)', string, (err, results) => {
        if (err) {
            console.error('Error inserting string into database:', err);
            return res.status(500).send('Failed to insert string into database');
        }

        console.log('String inserted successfully');
        return res.status(200).send('String inserted successfully');
    });
});

app.listen(port, () => {
    console.log(`Server is running on http://192.168.1.200:${port}`);
});

Errors with the current config above.

2

Answers


  1. Chosen as BEST ANSWER

    the 403 forbidden issue i solved by adding a Cloudflare page rule to

    https://myapp.exmaple.app/* Always Use HTTPS.

    I was able to insert into the DB from my webpage ONLY now with using "Allow CORS" google chrome extension.


  2. What you’ve done you just enforced CORS middleware without configuring anything. Check this link for more deep technical knowledge.

    However, below is CORS configuration blueprint that you can modify to accommodate your needs.

    const express = require("express");
    const app = express();
    app.use(express.json());
    
    // For CORS
    app.use((req, res, next) => {
      const allowedOrigins = [
        'http://example1.com',
        'https://example2.com',
        'http://localhost:3016' // allow local development server
      ];
    
      const origin = req.headers.origin;
    
      // Check if the request origin is in the list of allowed origins
      if (allowedOrigins.includes(origin)) {
        res.header("Access-Control-Allow-Origin", origin); // replace with '*' to allow all
      }
    
      res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // replace with '*' to allow all
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // replace with '*' to allow all
      res.header("Access-Control-Allow-Credentials", "true");
    
      next();
    });
    
    app.post("/api/v1/insert", async (req, res) => {
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search