Simplest example of server side script

Is there a simple way to create a server side script that I can call from my client side scripts?

I am using OpenAI and it uses a secret key to allow me to make API calls. It’s bad practice to put the secret key in client code so i need to make a simple relay on the server that i can call from my client script. It would add the appropriate cross origin headers and make the API call after adding the secret key. It would then return the result to the client.

Original Post on Discord

by user 563549194137239552

You can set up a simple server on https://glitch.com if you want and just call that

Of course you could also add that directly to a project you deploy somewhere, but we don’t have something automagic for this, depends too much on where you want to deploy and with what server language etc.

OpenAI wrote this for me… what a world we live in.

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

const app = express();
app.use(cors());

app.use((req, res, next) => {
  // Add CORS headers to the response
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

app.use('/', (req, res) => {
  // Relay the request to a different server
  axios({
    method: req.method,
    url: 'http://other-server.com' + req.url,
    data: req.body
  })
    .then(response => {
      // Return the response from the other server
      res.json(response.data);
    })
    .catch(error => {
      res.json(error);
    });
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

by user 563549194137239552

:slightly_smiling_face: looks good
for more production-y use you’ll want to limit the allowed origins to one you control though