Tampermonkey add global functions available in console

My problem was: I could only call the function for the first time when I press Ctrl Shift I to call out the console. After that, the function won’t work.

I faced this problem a few months ago and got an answer from here
How do I make functions added by Tampermonkey be available in console after the script has been ran?

I did it like this and my personal PC works:

let myFunctions = window.myFunctions = {};

myFunctions.onKeyDown = function () {
    const keyName = event.key;
    //console.log(keyName);

    if (keyName === "Alt") {
        return;
    }

    if (event.altKey) {
        switch (keyName) {
            case 'a':
                console.log("alt a pressed");
                return
            case 's':
                console.log("alt s pressed");
                return
        }
    }
}

document.addEventListener("keydown", myFunctions.onKeyDown, false);

And now, I faced the same problem again, in my office computer.
I used this code, exactly the same, still works for my home PC and not work for my office PC.
Tampermonkey setting exactly the same. Other functions in tampermonkey working (the scripted is inserted into the page)
I searched for other solutions. Unsafe Window does not work. Please offer help. Thank you!

Unable to access file while uploading via multer

I have created 2 routes the /upload is working fine i am able to upload image but /signup i am getting an empty obj in req.files and only able to access req.body

Here is my route.js file

const express = require("express");
const router = express.Router();
const app = express();
const multer = require("multer");

const storage = multer.memoryStorage();

const upload = multer({ storage });

let multiUpload = upload.fields([{ name: "photo", maxCount: 1 }]);
const { s3upload } = require("../middleware/awsService");

router.post("/signup", multiUpload, async (req, res) => {
  console.log(req.files);
  console.log(req.body);
  // const file = req.files.photo[0];
  // console.log(req.files.photo);
  const result = await s3upload(file);
  // console.log(req.files);
  // console.log(req.body);
  res.status(200).json({
    status: "success",
    message: "Upload successfull",
    result,
  });
});

router.post("/upload", multiUpload, async (req, res) => {
  const file = req.files.photo[0];
  console.log(req.files.photo);
  const result = await s3upload(file);
  console.log(req.files);
  console.log(req.body);
  res.status(200).json({
    status: "success",
    message: "Upload successfull",
    result,
  });
});

module.exports = router;

/upload is working fine but unable to upload file via /signup route

Why is mammoth unable to read the docx I’ve passed to the server?

I’m trying to provide a method to upload .docx files from the client to the server using next.js. At the server, I’d like to read the .docx using the mammoth library.

Front End Code

import {
    useMantineTheme,
    rem,
    Text,
    Group
} from '@mantine/core';

import {
    IconBook,
    IconUpload,
    IconX,
} from '@tabler/icons-react';

import { 
    Dropzone, 
    FileWithPath
} from '@mantine/dropzone';

import React, { useState } from "react"
import axios from "axios"

export default function Upload(this: any) {

    const theme = useMantineTheme();

    const [isUploading, setIsUploading] = useState<boolean>(false);

    const [hash, setHash] = useState<string>("");

    async function onDrop(files : FileWithPath[]): Promise<void> {
    setIsUploading(true);

    for(const index in files) {
        const file = files[index];
        const formData = new FormData();
        formData.append("file", file);

        try{
            await axios.post('api/pull-apart', formData, {
                headers: {
                    'content-type':'multipart/form-data'
                }
            });
        } catch(e:any) {
            console.error('There was an error uploading ', e.message);
        } finally {
            setIsUploading(false);
        }
    }
    }

    return (
    <Dropzone
        onDrop={(file) => onDrop(file)}
        onReject={(file) => console.log('rejected file', file)}
        accept={["application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "image/jpeg", "image/png"]}
        maxFiles={10}
    >
        <Group position="center" spacing="xl" style={{ minHeight: rem(80), pointerEvents: 'none' }}>
            <Dropzone.Accept>
                <IconUpload
                    size="3.2rem"
                    stroke={1.5}
                    color={theme.colors[theme.primaryColor][theme.colorScheme === 'dark' ? 4 : 6]}
                />
            </Dropzone.Accept>
            <Dropzone.Reject>
                <IconX
                    size="3.2rem"
                    stroke={1.5}
                    color={theme.colors.red[theme.colorScheme === 'dark' ? 4 : 6]}
                />
            </Dropzone.Reject>
            <Dropzone.Idle>
                <IconBook size="3.2rem" stroke={1.5} />
            </Dropzone.Idle>

            <div>
                <Text size="xl" inline>
                    Upload your .DOCX 
                </Text>
            </div>
        </Group>
    </Dropzone>
    )
}

Server Code pull-apart.ts

import type { NextApiRequest, NextApiResponse } from "next";
import formidable, { File } from 'formidable';
import fs from 'fs';

import mammoth from 'mammoth';

const form = formidable({multiples: true});

const isFile = (file: File | File[]): file is File => !Array.isArray(file) && file.filepath !== undefined;

type Data = {
    message?: string
} | any[];

const handler = async (req: NextApiRequest, res: NextApiResponse<Data>) => {
    if(req.method !== "POST") {
    return res.status(405).json({message: "Method Not Allowed"});
    }

    try {
    const fileContent: string = await(new Promise((resolve, reject) => {
        form.parse(req, (err, _fields, files) => {
            if(isFile(files.file)) {
                const fileContentBuffer = fs.readFileSync(files.file.filepath);
                const fileContentReadable = fileContentBuffer.toString("utf-8");

                resolve(fileContentReadable);
            }

            reject();
        });
    }));

    /* do something */

    console.log(fileContent);

    const b = Buffer.from(fileContent, 'utf-8');

    mammoth.convertToHtml(
        {buffer: b},
        {
            styleMap: [
                "p[style-name='Title'] => h1"
            ]
        }
    ).then(function(result:any){

        var html = result.value;
        console.log(html);
    
    }).catch(function(error:any){

        console.log(error);
    
    });

    res.status(200).send({message: 'ok'});
    } catch(e) {
    res.status(400).send({message: "Bad Request"});
    }
}

export const config = {
    api: {
    bodyParser: false
    }
};

export default handler;

The error message output on the server console is:

Error: End of data reached (data length = 10142, asked index = 15447). Corrupted zip ?

I’ve double checked that my test .docx is a well-formed .docx. I assume based on the error that the issue is the interpretation of the data being passed from client to server, but I can’t tell what the problem is.

As far as I can see, I’m successfully sending the file content to the server in binary form, where it’s then interpreted as a string of utf-8 character. This string is then turned into a Buffer to be passed to Mammoth.

Could anyone check my code to see what I did wrong?

I am new to coding and am messing around with a little project. It says there is something wrong with my syntax, but I do not know how to fix it, could anyone help? There are supposed to be pictures once I click on the corresponding album. Also, why is one of the labels in the hmtl not working?

https://codepen.io/SacredSoulrend/pen/poxOgrN?editors=1111

your text

There are supposed to be pictures once I click on the corresponding album title.

Handlebar table construction

I have a table where handlebar template is used. In the first row of the table each is declared and in the next row tokens are declared.

<table style="border-collapse: collapse; width: 100%;" border="1"><colgroup><col><col><col><col></colgroup>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4">{{#each itemList}}</td>
</tr>
<tr>
<td>{{name}}</td>
<td>{{price}}</td>
<td>{{qty}}</td>
<td>{{total}}</td>
</tr>
<tr>
<td colspan="4">{{/each}}</td>
</tr>
</tbody>
</table>

While compiling, the generated output look like this. the first table row where each is defined is not removed. is there any way to remove that?

<table style="border-collapse: collapse; width: 100%;" border="1" data-mce-style="border-collapse: collapse; width: 100%;">
  <colgroup>
    <col>
    <col>
    <col>
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>a</th>
      <th>c</th>
      <th>v</th>
      <th>d</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan="4">
        <tr>
          <td>12</td>
          <td>3</td>
          <td>2</td>
          <td>2</td>
        </tr>
      </td>
    </tr>
  </tbody>
</table>

Problem about read thai language text file and Insert text thai language in to database

  1. Use Javascript for coding

  2. Thai language text file is enconding with ANSI

  3. setting Collation in SQL is utf8_unicode_ci

  4. show text before insert to database it can be show thai language like this บริษัท

  5. I check in database it show ??????????????????

  6. show data from database show ??????????????????

  7. It is my coding

//Connect data base
            Connection connect = null;
            Statement s = null;    
            Class.forName("com.mysql.jdbc.Driver");
            connect =  DriverManager.getConnection("jdbc:mysql");
            s = connect.createStatement();      

//import txt file             
            FileInputStream file = new FileInputStream("text.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(file));
            String line;
            int i=0;
            
//loop while read txt file
            while((line = reader.readLine())!= null)
            {
                int flag=0;
                String sql = "";
                String tbInsert = "";

 //loop for cut | and insertา Array               
                String[] split = line.split("\|");               
             
                for (i = 0; i<split.length; i++)
                {
 
//loop for cut black space               
                    split[i] = split[i].trim();

//read data
                    if(split[0].substring(0,3).equals("001") && flag==0)
                    { 
                   
                        tbInsert = "header";
                        String SQL_INSERT = "INSERT INTO header (Record_Type,Sender,Data_Date,Create_Date,Create_Time) VALUES (?,?,?,?,?)";
                        PreparedStatement preparedStatement = connect.prepareStatement(SQL_INSERT);
                        
                        for (int j = 0; j < 5; j++) {
                            preparedStatement.setString(j + 1, new String(split[j]));
                        }

                        int row = preparedStatement.executeUpdate();
                    }

                     if(split[0].substring(0,3).equals("999") && flag==0) 
                    {
                        tbInsert = "summary";
                        String SQL_INSERT = "INSERT INTO summary (Record_Type,Record_Type_002,Summary_Record_Type_002,Record_Type_003,Summary_Record_Type_003,Record_Type_004,Summary_Record_Type_004) VALUES (?,?,?,?,?,?,?)";
                        PreparedStatement preparedStatement = connect.prepareStatement(SQL_INSERT);

                        for (int j = 0; j < 7; j++) {
                            preparedStatement.setString(j + 1, new String(split[j]));
                        }

                        int row = preparedStatement.executeUpdate();
                    } 
                    flag++;    
                } 
            }

how to solv database can insert and read thai language

registering callback functions in embedded quickjs project

so I’ve had a look online and can’t really find much. I was hoping someone might have experience setting up a .registerCallback() method in an embedded quickjs project.

the type of use would be like this in the script:

import {Class} from 'Class'
let c = new Class();
c.registerCallback(callbackfunc);

function callbackfunc() {}

the addCallbackMethod in the cpp file:

// Custom method function: Performs a custom operation on the object
static JSValue myClass_addCallbackMethod(
    JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
    auto* object = static_cast<myClassData *>(
        JS_GetOpaque2(ctx, this_val, myClassId));

    // If no callback function is provided or the provided argument is not a function, return an exception
    if (argc == 0 || !JS_IsFunction(ctx, argv[0]))
        return JS_ThrowTypeError(ctx, "Expected a function as argument");

    // Store the callback function in the object
    object->registeredCallback = JS_DupValue(ctx, argv[0]);

    return JS_UNDEFINED;
}```




I've had a go and I thought I was on the right track but it seems to give me seg faults whenever I try and access the object's property that's holding the function in my main.cpp

How to parse array variable into a .show() pop up in webix?

I have a code like this.

$$('TLVab').attachEvent("onAfterEditStop", function(state, editor, ignoreUpdate) {
    if(state.value == state.old) return;
    if(editor.column == 'mcns' && state.old.length > 1)  {
      let newv = state.value.split(",");
      let todel = [];
      for(let i=0; i<state.old.length; i++) {
        if(!newv.includes(state.old[i])) {
          todel.push(state.old[0]);
        }
      }
      if(todel.length > 0)  {
        $$('deleteLTMPopup').show();//TODO parse todel into the pop up      
}
    }
  });

UI.deleteLTMPopup= {id:'deleteLTMPopup',view:'window',head:'D',modal:true,position:'center',resize:true,move:true,autowidth:true,body:
    {rows:[
      {id:'delLifeTimeMCN',template:'W'},
      {cols:[
        {},
        {view:'button',value:'Cancel',width:60,click:function(){ this.getTopParentView().hide()}},
        {id:'deleteLTMBtnOK',view:'button',value:'Delete',width:60,click:function(id){
          var that = this;
          myFunction();//TODO have to parse todel
          that.getTopParentView().hide();
        }},
      ]},
    ]}
  };

How do I pass todel variable into the popup? I mean is there a .show(todel) something like that. I have added //TODO inline comments in my code.

Intro.js onbeforechange function, cannot go to the step that in actual behaviour we have to click to see that part

Im using intojs, the step 1 and 2 are okay then when to travel to step 3 from step 2, I faced a problem to travel to step 3. For the normal behavior, we have to click first then step 3 part will be shown. Actually, step 3 is the 3 dot button, when we click that 3 dot button, it will show some functions like log out and my profile.

This the class that makes the part is shown
“dropdown profile_menu open”
and this is the code if it does not show
“dropdown profile_menu”

This is my js code:

<script type="text/javascript">
    $(document).ready(function () {
        var intro = introJs();
        intro.setOptions({
            steps: [
                {
                    element: '#divSideBar',
                    intro: '<strong>Fixing Sidebar</strong> <br/> This is the side bar of the system',
                },
                {
                    element: '#divTopBar',
                    intro: '<strong>Shortcut</strong> <br/>1. Dashboard<br/>2. Profile Search<br/>3. Inbox<br/>4. Org Chart<br/>5. Report',
                    onbeforechange: function () {
                        console.log('Opening dropdown menu');
                        $('#liUserNav').click(); // replace #profile-menu-button with the ID of the button that opens the dropdown menu
                        setTimeout(function () {
                            intro.nextStep();
                        }, 1000); // wait for 1 second for the dropdown menu to appear
                    },
                    onshow: function () {
                        $('.dropdown.profile_menu').addClass('open');
                    }
                },
                {
                    element: '#divProfile',
                    intro: '<strong>Profile</strong> <br/>Your Profile',
                    onshow: function () {
                        $('.dropdown.profile_menu').addClass('open');
                    }
                }
            ]
        });
        introJs().setOption('showBullets', false).setOptions({ scrollToElement: false }).start();
    });
</script>

Video editor scripting windows

i want to use a program to automate cutting my videos into different shots with random lengths, scales/positions, and compositing effects and filters in order to replicate the editing process I go through to make music videos on Tiktok.

tried using blender with python but API seemed too limited. I am new to coding but its pretty interesting to me so I want to find a free and accessible way to achieve this idea.

Problem regarding signup form submission data not being received in the backend

I am following a video course for creation of an Online exam portal using Angular for frontend and Springboot for backend along with MySQl for DB. We have been shown how to create the backend code for adding a new user and have tested that it is indeed working through the Postman app. However while trying to do the same through the frontend signup form I am facing this issue :-

Error shown in console

Here’s the same POST request being sent through Postman app which works and updates the database:-

Users Table updated successfully through sending the request using Postman

My frontend file hierarchy

My “signup.component.ts” file:-

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {

  constructor(private userService:UserService){}

  public user={
    username:'',
    password:'',
    firstname:'',
    lastname:'',
    email:'',
    mobile:''
  }

  ngOnInit():void{}

  formSubmit(){
    
    console.log(this.user);
    if(this.user.username == '' || this.user.username == null){
      alert('User Name Field cannot be blank!');
      return;
    }

    //addUser:UserService
    
      this.userService.addUser(this.user).subscribe(
        {
          next: (data) => console.log(data),
          error: (err) => console.log(err),
          complete: () => console.log("completed")
        });

  }

}

My “helper.ts” file :-

 let baseUrl="http//:localhost:8080"
 export default baseUrl

My “user.service.ts” file :-

 import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private http:HttpClient) { }

public addUser (user:any){
  return this.http.post('${baseUrl}/user/',user);
}

}

Backend file hierarchy

My “UserController.java” file :-

package com.exam.controller;

import com.exam.entity.Role;
import com.exam.entity.User;
import com.exam.entity.UserRole;
import com.exam.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Set;


@CrossOrigin(allowCredentials = "")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //create user
    @PostMapping("/")
    public User createUser(@RequestBody User user) throws Exception {

        Role role = new Role();
        role.setRoleID(191001001105L); //Default role id set
        role.setRoleName("NORMAL");

        UserRole userRole= new UserRole();
        userRole.setUser(user);
        userRole.setRole(role);

        Set<UserRole> roles= new HashSet<>();
        roles.add(userRole);

        return this.userService.createUser(user,roles);
    }

    //get user by username
    @GetMapping("/{username}")
    public User getUser(@PathVariable("username") String username){
        return this.userService.getUser(username);
    }

    //delete user by Id
    @DeleteMapping("/{userId}")
    public void deleteUser(@PathVariable("userId") Long userId){
        this.userService.deleteUser(userId);
    }

}

My Apache Tomcat Server is running on port 8080 while the Angular Development Server is running on 4200.

Any help regarding this issue will be much appreciated!

API server call to OpenAI “An error occurred during the API call: Request failed with status code 404”

I’m attempting to use the OpenAI chat api in my code, but keep getting a 404 error. This is my server.js (With my api key removed which is definitely valid, I’ve triple checked).

const express = require('express');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
const { Configuration, OpenAIApi } = require('openai');

dotenv.config();

const app = express();
const port = process.env.PORT || 3001;

app.use(bodyParser.json());

const configuration = new Configuration({
  apiKey: 'removed',
});

const openai = new OpenAIApi(configuration);

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

app.post('/api/chat', async (req, res) => {
  try {
    const { input } = req.body;

    const response = await openai.createChatCompletion({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: input }],
    });

    const aiMessage = response.data.choices[0].message.content.trim();
    res.json({ aiMessage });
  } catch (error) {
    console.error('Error in API call:', error);
    res.status(500).json({ error: 'An error occurred during the API call' });
  }
});

If I call the endpoint with Postman, I get this extremely long error in my server log.

[1] Error in API call: Error: Request failed with status code 400
[1]     at createError (C:UsersTheNomadicAspieDesktopmenu-appnode_modulesaxioslibcorecreateError.js:16:15)
[1]     at settle (C:UsersTheNomadicAspieDesktopmenu-appnode_modulesaxioslibcoresettle.js:17:12)
[1]     at IncomingMessage.handleStreamEnd (C:UsersTheNomadicAspieDesktopmenu-appnode_modulesaxioslibadaptershttp.js:322:11)
[1]     at IncomingMessage.emit (node:events:525:35)
[1]     at endReadableNT (node:internal/streams/readable:1359:12)
[1]     at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {[1]   config: {
[1]     transitional: {
[1]       silentJSONParsing: true,
[1]       forcedJSONParsing: true,
[1]       clarifyTimeoutError: false
[1]     },
[1]     adapter: [Function: httpAdapter],
[1]     transformRequest: [ [Function: transformRequest] ],
[1]     transformResponse: [ [Function: transformResponse] ],
[1]     timeout: 0,
[1]     xsrfCookieName: 'XSRF-TOKEN',
[1]     xsrfHeaderName: 'X-XSRF-TOKEN',
[1]     maxContentLength: -1,
[1]     maxBodyLength: -1,
[1]     validateStatus: [Function: validateStatus],
[1]     headers: {
[1]       Accept: 'application/json, text/plain, */*',
[1]       'Content-Type': 'application/json',
[1]       'User-Agent': 'OpenAI/NodeJS/3.2.1',
[1]       Authorization: 'Bearer removed',  
[1]       'Content-Length': 54
[1]     },
[1]     method: 'post',
[1]     data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user"}]}',
[1]     url: 'https://api.openai.com/v1/chat/completions'
[1]   },
[1]   request: <ref *1> ClientRequest {
[1]     _events: [Object: null prototype] {
[1]       abort: [Function (anonymous)],
[1]       aborted: [Function (anonymous)],
[1]       connect: [Function (anonymous)],
[1]       error: [Function (anonymous)],
[1]       socket: [Function (anonymous)],
[1]       timeout: [Function (anonymous)],
[1]       finish: [Function: requestOnFinish]
[1]     },
[1]     _eventsCount: 7,
[1]     _maxListeners: undefined,
[1]     outputData: [],
[1]     outputSize: 0,
[1]     writable: true,
[1]     destroyed: false,
[1]     _last: true,
[1]     chunkedEncoding: false,
[1]     shouldKeepAlive: false,
[1]     maxRequestsOnConnectionReached: false,
[1]     _defaultKeepAlive: true,
[1]     useChunkedEncodingByDefault: true,
[1]     sendDate: false,
[1]     _removedConnection: false,
[1]     _removedContLen: false,
[1]     _removedTE: false,
[1]     strictContentLength: false,
[1]     _contentLength: 54,
[1]     _hasBody: true,
[1]     _trailer: '',
[1]     finished: true,
[1]     _headerSent: true,
[1]     _closed: false,
[1]     socket: TLSSocket {
[1]       _tlsOptions: [Object],
[1]       _secureEstablished: true,
[1]       _securePending: false,
[1]       _newSessionPending: false,
[1]       _controlReleased: true,
[1]       secureConnecting: false,
[1]       _SNICallback: null,
[1]       servername: 'api.openai.com',
[1]       alpnProtocol: false,
[1]       authorized: true,
[1]       authorizationError: null,
[1]       encrypted: true,
[1]       _events: [Object: null prototype],
[1]       _eventsCount: 10,
[1]       connecting: false,
[1]       _hadError: false,
[1]       _parent: null,
[1]       _host: 'api.openai.com',
[1]       _closeAfterHandlingError: false,
[1]       _readableState: [ReadableState],
[1]       _maxListeners: undefined,
[1]       _writableState: [WritableState],
[1]       allowHalfOpen: false,
[1]       _sockname: null,
[1]       _pendingData: null,
[1]       _pendingEncoding: '',
[1]       server: undefined,
[1]       _server: null,
[1]       ssl: [TLSWrap],
[1]       _requestCert: true,
[1]       _rejectUnauthorized: true,
[1]       parser: null,
[1]       _httpMessage: [Circular *1],
[1]       [Symbol(res)]: [TLSWrap],
[1]       [Symbol(verified)]: true,
[1]       [Symbol(pendingSession)]: null,
[1]       [Symbol(async_id_symbol)]: 25,
[1]       [Symbol(kHandle)]: [TLSWrap],
[1]       [Symbol(lastWriteQueueSize)]: 0,
[1]       [Symbol(timeout)]: null,
[1]       [Symbol(kBuffer)]: null,
[1]       [Symbol(kBufferCb)]: null,
[1]       [Symbol(kBufferGen)]: null,
[1]       [Symbol(kCapture)]: false,
[1]       [Symbol(kSetNoDelay)]: false,
[1]       [Symbol(kSetKeepAlive)]: true,
[1]       [Symbol(kSetKeepAliveInitialDelay)]: 60,
[1]       [Symbol(kBytesRead)]: 0,
[1]       [Symbol(kBytesWritten)]: 0,
[1]       [Symbol(connect-options)]: [Object]
[1]     },
[1]     _header: 'POST /v1/chat/completions HTTP/1.1rn' +
[1]       'Accept: application/json, text/plain, */*rn' +
[1]       'Content-Type: application/jsonrn' +
[1]       'User-Agent: OpenAI/NodeJS/3.2.1rn' +
[1]       'Authorization: Bearer removedrn' +
[1]       'Content-Length: 54rn' +
[1]       'Host: api.openai.comrn' +
[1]       'Connection: closern' +
[1]       'rn',
[1]     _keepAliveTimeout: 0,
[1]     _onPendingData: [Function: nop],
[1]     agent: Agent {
[1]       _events: [Object: null prototype],
[1]       _eventsCount: 2,
[1]       _maxListeners: undefined,
[1]       defaultPort: 443,
[1]       protocol: 'https:',
[1]       options: [Object: null prototype],
[1]       requests: [Object: null prototype] {},
[1]       sockets: [Object: null prototype],
[1]       freeSockets: [Object: null prototype] {},
[1]       keepAliveMsecs: 1000,
[1]       keepAlive: false,
[1]       maxSockets: Infinity,
[1]       maxFreeSockets: 256,
[1]       scheduling: 'lifo',
[1]       maxTotalSockets: Infinity,
[1]       totalSocketCount: 1,
[1]       maxCachedSessions: 100,
[1]       _sessionCache: [Object],
[1]       [Symbol(kCapture)]: false
[1]     },
[1]     socketPath: undefined,
[1]     method: 'POST',
[1]     maxHeaderSize: undefined,
[1]     insecureHTTPParser: undefined,
[1]     joinDuplicateHeaders: undefined,
[1]     path: '/v1/chat/completions',
[1]     _ended: true,
[1]     res: IncomingMessage {
[1]       _readableState: [ReadableState],
[1]       _events: [Object: null prototype],
[1]       _eventsCount: 4,
[1]       _maxListeners: undefined,
[1]       socket: [TLSSocket],
[1]       httpVersionMajor: 1,
[1]       httpVersionMinor: 1,
[1]       httpVersion: '1.1',
[1]       complete: true,
[1]       rawHeaders: [Array],
[1]       rawTrailers: [],
[1]       joinDuplicateHeaders: undefined,
[1]       aborted: false,
[1]       upgrade: false,
[1]       url: '',
[1]       method: null,
[1]       statusCode: 400,
[1]       statusMessage: 'Bad Request',
[1]       client: [TLSSocket],
[1]       _consuming: false,
[1]       _dumped: false,
[1]       req: [Circular *1],
[1]       responseUrl: 'https://api.openai.com/v1/chat/completions',
[1]       redirects: [],
[1]       [Symbol(kCapture)]: false,
[1]       [Symbol(kHeaders)]: [Object],
[1]       [Symbol(kHeadersCount)]: 40,
[1]       [Symbol(kTrailers)]: null,
[1]       [Symbol(kTrailersCount)]: 0
[1]     },
[1]     aborted: false,
[1]     timeoutCb: null,
[1]     upgradeOrConnect: false,
[1]     parser: null,
[1]     maxHeadersCount: null,
[1]     reusedSocket: false,
[1]     host: 'api.openai.com',
[1]     protocol: 'https:',
[1]     _redirectable: Writable {
[1]       _writableState: [WritableState],
[1]       _events: [Object: null prototype],
[1]       _eventsCount: 3,
[1]       _maxListeners: undefined,
[1]       _options: [Object],
[1]       _ended: true,
[1]       _ending: true,
[1]       _redirectCount: 0,
[1]       _redirects: [],
[1]       _requestBodyLength: 54,
[1]       _requestBodyBuffers: [],
[1]       _onNativeResponse: [Function (anonymous)],
[1]       _currentRequest: [Circular *1],
[1]       _currentUrl: 'https://api.openai.com/v1/chat/completions',
[1]       [Symbol(kCapture)]: false
[1]     },
[1]     [Symbol(kCapture)]: false,
[1]     [Symbol(kBytesWritten)]: 0,
[1]     [Symbol(kEndCalled)]: true,
[1]     [Symbol(kNeedDrain)]: false,
[1]     [Symbol(corked)]: 0,
[1]     [Symbol(kOutHeaders)]: [Object: null prototype] {
[1]       accept: [Array],
[1]       'content-type': [Array],
[1]       'user-agent': [Array],
[1]       authorization: [Array],
[1]       'content-length': [Array],
[1]       host: [Array]
[1]     },
[1]     [Symbol(errored)]: null,
[1]     [Symbol(kUniqueHeaders)]: null
[1]   },
[1]   response: {
[1]     status: 400,
[1]     statusText: 'Bad Request',
[1]     headers: {
[1]       date: 'Tue, 16 May 2023 02:22:58 GMT',
[1]       'content-type': 'application/json',
[1]       'content-length': '160',
[1]       connection: 'close',
[1]       'access-control-allow-origin': '*',
[1]       'openai-organization': 'user-tblz934t92ja8twwukcaheq7',
[1]       'openai-processing-ms': '208',
[1]       'openai-version': '2020-10-01',
[1]       'strict-transport-security': 'max-age=15724800; includeSubDomains',
[1]       'x-ratelimit-limit-requests': '3500',
[1]       'x-ratelimit-limit-tokens': '90000',
[1]       'x-ratelimit-remaining-requests': '3499',
[1]       'x-ratelimit-remaining-tokens': '89983',
[1]       'x-ratelimit-reset-requests': '17ms',
[1]       'x-ratelimit-reset-tokens': '11ms',
[1]       'x-request-id': '9291039cf2af6385af913b1be36d2803',
[1]       'cf-cache-status': 'DYNAMIC',
[1]       server: 'cloudflare',
[1]       'cf-ray': '7c8027ec5fca09f1-LAS',
[1]       'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'
[1]     },
[1]     config: {
[1]       transitional: [Object],
[1]       adapter: [Function: httpAdapter],
[1]       transformRequest: [Array],
[1]       transformResponse: [Array],
[1]       timeout: 0,
[1]       xsrfCookieName: 'XSRF-TOKEN',
[1]       xsrfHeaderName: 'X-XSRF-TOKEN',
[1]       maxContentLength: -1,
[1]       maxBodyLength: -1,
[1]       validateStatus: [Function: validateStatus],
[1]       headers: [Object],
[1]       method: 'post',
[1]       data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user"}]}',
[1]       url: 'https://api.openai.com/v1/chat/completions'
[1]     },
[1]     request: <ref *1> ClientRequest {
[1]       _events: [Object: null prototype],
[1]       _eventsCount: 7,
[1]       _maxListeners: undefined,
[1]       outputData: [],
[1]       outputSize: 0,
[1]       writable: true,
[1]       destroyed: false,
[1]       _last: true,
[1]       chunkedEncoding: false,
[1]       shouldKeepAlive: false,
[1]       maxRequestsOnConnectionReached: false,
[1]       _defaultKeepAlive: true,
[1]       useChunkedEncodingByDefault: true,
[1]       sendDate: false,
[1]       _removedConnection: false,
[1]       _removedContLen: false,
[1]       _removedTE: false,
[1]       strictContentLength: false,
[1]       _contentLength: 54,
[1]       _hasBody: true,
[1]       _trailer: '',
[1]       finished: true,
[1]       _headerSent: true,
[1]       _closed: false,
[1]       socket: [TLSSocket],
[1]       _header: 'POST /v1/chat/completions HTTP/1.1rn' +
[1]         'Accept: application/json, text/plain, */*rn' +
[1]         'Content-Type: application/jsonrn' +
[1]         'User-Agent: OpenAI/NodeJS/3.2.1rn' +
[1]         'Authorization: Bearer removedrn' +
[1]         'Content-Length: 54rn' +
[1]         'Host: api.openai.comrn' +
[1]         'Connection: closern' +
[1]         'rn',
[1]       _keepAliveTimeout: 0,
[1]       _onPendingData: [Function: nop],
[1]       agent: [Agent],
[1]       socketPath: undefined,
[1]       method: 'POST',
[1]       maxHeaderSize: undefined,
[1]       insecureHTTPParser: undefined,
[1]       joinDuplicateHeaders: undefined,
[1]       path: '/v1/chat/completions',
[1]       _ended: true,
[1]       res: [IncomingMessage],
[1]       aborted: false,
[1]       timeoutCb: null,
[1]       upgradeOrConnect: false,
[1]       parser: null,
[1]       maxHeadersCount: null,
[1]       reusedSocket: false,
[1]       host: 'api.openai.com',
[1]       protocol: 'https:',
[1]       _redirectable: [Writable],
[1]       [Symbol(kCapture)]: false,
[1]       [Symbol(kBytesWritten)]: 0,
[1]       [Symbol(kEndCalled)]: true,
[1]       [Symbol(kNeedDrain)]: false,
[1]       [Symbol(corked)]: 0,
[1]       [Symbol(kOutHeaders)]: [Object: null prototype],
[1]       [Symbol(errored)]: null,
[1]       [Symbol(kUniqueHeaders)]: null
[1]     },
[1]     data: { error: [Object] }
[1]   },
[1]   isAxiosError: true,
[1]   toJSON: [Function: toJSON]
[1] }

I’ve looked at answers from people with similar problems, and tried various models and methods of calling open including calling the url directly. I’m not sure what I’m doing wrong, how can I troubleshoot this?