Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet:

var rating = document.getElementById("rating");
var ratingValue = rating.innerHTML;
fetch("/films",{
    method: "post",
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        rated : ratingValue
    })
})

However, upon trying to retrieve this data on my server, an error is encountered:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

The corresponding server-side code looks like this:

app.post("/films", function(req,res){
    var rating = req.body.rated;
    ...
})

The issue seems to arise from the first line within the function, specifically when declaring the rating variable.

Answer №1

When you define

var rating = document.getElementById("rating");
, you are selecting an HTML element that might look something like this:
<div id='rating'>Some text</div>
. It's important to note that I don't have information on what the content of the rating element is, or its data type, so this is simply an example. In a later part of your code, you are using rating as a key in:

 body: JSON.stringify({
        rating : ratingValue
 })

This means you are attempting to create a key-value pair similar to:

{ "<div id='rating'>Some Text</div>" : ratingValue }

The error indicating a < symbol at position 0 corresponds to the presence of a < at the start of your key. This could be contributing to the error. Are you intending to use the value within the rating element as the key for your body?

*Update 5-25-2020*

If the element with the ID 'rating' contains nested elements, it may cause issues if you only require a simple value.

//This setup can pose problems if the innerHTML of 'rating' is <p>10</p>
<div id='rating'>
     <p>10</p>
</div>

The following example should function correctly if 'ratingValue' expects a number and the innerHTML of 'rating' is 10. You might need to parse the innerHTML using parseInt(), but give it a try without first.

<div id='rating'>
     10
</div>

Please remember that this is just a hypothetical scenario since I don't have details about the type of element attached to the 'rating' ID.

Answer №2

Is it possible that you intended to write req.body.rating instead?

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

Transfer information from an Express route to a function exported from a Node module

I'm new to using node.js and I've been told that I need to use middleware, but I'm having trouble understanding its purpose and the proper way to implement it. I have data that is being sent from my view to an express route. ROUTE - route.j ...

Creating a controlled unit test that utilizes rollback functionality in a project involving express, sequelize, mocha, and supertests

I am currently experimenting with testing data insertion into a database, using supertest to test a request, and then performing a rollback with the fake data. Can anyone confirm if this approach is correct? If not, could you please provide guidance on t ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

Exporting variables in node.js allows you to share data between different

Hi, I'm currently working with a file that looks like this: module.exports = { some variables that are being exported here, execute(message) { } } I want to export the message parameter to another file. I've attempted using var msg ...

How to Share Your Vuejs Component with the World by Publishing it on npm

I have recently developed a Vue.js 2 project using webpack which consists of 2 components. My goal is to share this project as an npm package so that the components can be easily reused in multiple projects. After publishing the project on npm with npm pu ...

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

Tree Grid in jqGrid with Offline Data

Accessing the jqGrid documentation for tree grid, I discovered the following information: "At present, jqGrid can only interact with data that is returned from a server. However, there are some tips and resources available that explain how to work w ...

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

Can a robust web application be developed using Kotlin in Node.js?

With the recent release of Kotlin 1.1, it is now possible to compile Kotlin projects into JavaScript as a target, allowing for full JavaScript compilation. Can a Node.js application, like an express webserver, be developed entirely using Kotlin code? As s ...

Utilizing Google Caja for JavaScript sanitization is the only way to ensure

Looking to safeguard the inputs provided to a nodejs server with the assistance of the google-caja sanitizer. However, it's somewhat overzealous and cleanses away the > and < symbols too. My project requires me to retain html characters in the ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

Using the function to show content by calling its assigned ID

<script type="text/javascript"> function selectRow(id){ $.get("http://inactive/test.php?id=" + id, function(data,status){ return data; }); } </script> <script type="text/javascript"> $("tr").click(function() { window.l ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

The DELETE request in my app using React Native and Fetch API is experiencing difficulties, although it is successfully working when tested in

We are facing an issue with our API while querying through React Native. Surprisingly, GET and POST requests work perfectly fine in both our app and Postman. However, the DELETE functionality seems to be failing on the app, even though the same request w ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

Can someone please advise me on how to output the value of a var_dump for an array using console.log?

After writing the code in this manner, it functions properly and returns a JSON object. public function getElementsAction() { $currency = App::$app->getProperty('currency'); if(!empty($_POST)) { $sql = 'SELECT name, p ...

What are all the different methods I can use to transfer element A to element B, and what are those methods?

While experimenting with Jquery, I encountered a roadblock and now have this question in mind. I wish to enclose all the anchor elements within a newly created div element. <td class="cont-mod-none-options" valign="top" align="right"> <a hr ...