The database was successfully updated; however, the API encountered a 500 error when trying to access

Currently, I am working on a project that utilizes Javascript alongside Node.js, Express, SuperAgent, and KnexJS for database management with Sqlite3. The issue I am facing is as follows:

Upon submitting data for updates through my API route using the PUT method, the database successfully updates but an error is displayed in the console:

PUT http://localhost:3000/user/contracts/ 500 (unknown)
Error: unknown
    at Request.<anonymous> (client.js:423)
    at Request.Emitter.emit (index.js:133)
    at XMLHttpRequest.xhr.onreadystatechange (client.js:735)

Below are snippets of the code from my API, Routes, and Database:

api.js

const request = require('superagent')

const updateUserContract = (callback, id, contractData) => {
  request
    .put('http://localhost:3000/user/contracts/' + id)
    .set('Content-Type', 'application/json')
    .send(contractData)
    .end(function (err, res) {
      if (err) {
        callback(err)
      } else {
        callback(null, "Status: 200")
      }
    })
}

module.exports = { updateUserContract }

routes.js

router.put('/contracts/:id', function (req, res) {
  var id = req.params.id
  var signatureUrl = req.body.signature_url
  db.signContract(id, signatureUrl).then((result) => {
    res.sendStatus(result)
  })
  .catch((err) => {
    res.status(500).send(err)
  })
})

db.js

function signContract (id, signatureUrl) {
  return knex('contracts').where('id', id)
  .update({ signature_url: signatureUrl }).into('contracts')
}

Answer №1

Responded by @Sombriks, addressing the error in question and suggesting a solution. According to them, sending sql status as an http status may lead to it being misinterpreted as an error 500. Their recommendation is to simply use req.send("OK"), which will result in default status 200 being delivered.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Can anyone provide guidance on removing a specific id from a mongoose document? Edit: I'm having trouble getting this to work (see edit)

Currently, I have a schema that looks something like this: user:{ _id: string, shifts:[_id:string], name: ... , ... } Now, my goal is to remove a shift._id from all users who have it. I already have an array containing the us ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...

JavaScript allows for selecting individual IDs by their corresponding numbers

Looking to retrieve numerical IDs <div class="user-view"> <div class="show_user_div"> <div class="disp"> <a href="/profile/name1/">name1</a><br /> <span id="show_a_3"> <a id="ref_show(3)">Show Details</ ...

Leveraging the useContext and useReducer hooks within NextJS, while encountering the scenario of reading null

Trying to develop a tic-tac-toe game in NextJS and setting up a board context for my components to access. However, after integrating a reducer into the Wrapper to handle a more complex state, I'm encountering a null error. Errors: TypeError: Cannot r ...

Showing a restricted number of rows in the JSP page

<table class="grid_alt" cellspacing="0" rules="all" border="1" id="id1" style="width:720px;border-collapse:collapse;"> <tbody> <tr align="left"> <th scope="col"><%=partner %></th><th scope="col"><%=item %>< ...

Missing Personal toolbar button on Forge Viewer interface

After completing the tutorial for learning Autodesk Forge, I successfully linked my BIM 360 account to the Forge Viewer. My next goal is to add extensions and have a button on the toolbar that directs to these extensions. However, when following the exten ...

When running `npm run dev` on webpack-dev-server, I encountered a TypeError stating that the property `port` cannot be set on an

Running node v10.15.1, vue js, vue-cli, and vue-loader with webpack, http-proxy-middleware (included) on a local win10 x64 remote host has been successful. Bootstrap v4 and bootstrap-vue were also installed and imported correctly. However, upon running np ...

Best practices for integrating JavaScript with PHP and MySQL

When it comes to inserting data into a MySQL database from JavaScript, I typically use AJAX with jQuery's $.POST function and PHP's mysqli function. This allows me to send the data to a PHP script which then inserts it into the database. Here is ...

Maximizing the efficiency of a personalized hook that facilitates data sharing in React

I have developed a unique Custom Hook that looks like the following: import { useEffect, useState } from 'react'; import axios from 'axios'; const myCustomHook = () => { const [countries, setCountries] = useState([]); const [i ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

Maximizing Efficiency: Sending Multiple Responses during computation with Express.js

Seeking a way to send multiple responses to a client while computing. See the example below: app.get("/test", (req, res) => { console.log('test'); setTimeout(() => { res.write('Yep'); setTime ...

Displaying that the response from ajax is experiencing issues

I am currently attempting to update the td elements in a table but my current method is not yielding successful results. Here's what I have tried: <table id="job1"> <tr><td></td></tr> <tr id="Jobstatus1"> ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Best practices for including jQuery in ASP.NET (or any other external JavaScript libraries)

Can you explain the distinctions among these three code samples below? Is there a preferred method over the others, and if so, why? 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", Re ...

The utilization of 'ref' with React Styled Components is proving to be ineffective

Using refs in Styled Components has been tricky for me. When I attempt to access them in my class methods as shown below, I encounter the error message: Edit.js:42 Uncaught TypeError: this.....contains is not a function constructor(props) { .... ...