The JSON is invalid due to an unexpected character at the beginning

I am encountering an issue with a POST method, even though I believe I have implemented it correctly.

Error:

Unexpected token f in JSON at position 1
at JSON.parse

This error seems to make sense in some way, as 'token f' aligns with the beginning of my data: field1: "##########"

Here is the post function for my API:

var putNewNums = (data) => {
    fetch('/getnums', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
    })
    .then(res => res.send())
}

This function points to the following route:

app.use('/getnums', getRouter)

which leads to this controller:

router.post('/', mainController.postNums)

The code for the controller is as follows:

postNums: (req, res, next) => {
    numSchem.create({
        field1: req.body.field1
    })
    .then(data => res.status(200).json(data))
    .catch(e => {
        req.error = e
        console.log(e)
        next()
    })
}

I am uncertain about where the error lies. I am passing a string just like my schema specifies:

const nums = mongoose.Schema ({
    field1: String,
})

Any insights on what might be incorrect in my implementation?

EDIT:

After updating req.boy to req.body.field1 in the postNums function, I encountered the following error:

{ ValidationError: numSchema validation failed: field1: Cast to String failed for value "{ field1: '8773238968' }" at path "field1"
at ValidationError.inspect (/Users/reid/Desktop/DupeFinder/server/node_modules/mongoose/lib/error/validation.js:59:24)
//Additional error details omitted for brevity

Answer №1

Solved the problem.

After using console.log(JSON.stringify(data)), I discovered that there was a duplicate field1 with the value: "field1" : "field1" : "phone number here"

There were two instances of field1 present.

To resolve this issue, I made the adjustment to use JSON.stringify(data.field1) instead of JSON.stringify(data), although I believe there may be multiple solutions to fix it.

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

Moving Configuration Files in NextJS

When working on a typical Next.js project, I often end up with several root-level configuration files: tsconfig.json next.config.js next-seo-config.ts .eslintrc etc... I am looking to tidy up my root directory by moving these files into their own separat ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

Pressing the "Enter" key will trigger a JavaScript function while the textbox is in focus

I am looking to enhance my search functionality on my website. <div class="TextField Large"> <input type="text" name="q" id="SearchBox" /> </div> <div style="height: 40px; text-align: right; position: absolute; top: 0px; right: 0p ...

The i18n feature in node.js seems to be malfunctioning as the setLocale function is not working properly. Regardless

Something seems off with my usage of the i18n library, but I believe I'm following the correct steps. I've been attempting to switch the locale. Here's my current code. Despite calling setLocale on the global i81n variable, it continues to ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

Issue with Selenium locating element within a GWT application

Looking to extract the text/value from an Element in a GWT app. You can find the app and the Element at the following locations: -navigate to -select "Products" -select "Software" -select "Rotary indexing table" -select "Next" -select "Next" again Y ...

Utilizing React to implement a search functionality with pagination and Material UI styling for

My current project involves retrieving a list of data and searching for a title name from a series of todos Here is the prototype I have developed: https://codesandbox.io/s/silly-firefly-7oe25 In the demo, you can observe two working cases in App.js & ...

Implementing a Class on Page Refresh in Next JS

I am fairly new to using react and nextjs. How can I insert a script in a component to add a class when the page reloads? The code below doesn't seem to work because the page is not yet rendered when I try to add the class for the body tag. const Mode ...

In React Native, I must include individual radio buttons for each item retrieved from the API

When I select a radio button on mobile, all radio buttons get selected instead of just the one clicked. Here is the current behavior: https://i.stack.imgur.com/qRJqV.jpg The expected behavior is to have only the clicked radio button selected, like in thi ...

vue-router incorrectly updates parameters upon reload

One question I have is related to routing in Vue.js: // routes.js { path: '/posts', name: 'Posts', component: PostsView }, { path: '/post/:post_id', name: 'PostRead', component: PostReadView, }, { pat ...

Having trouble loading images in JavaScript due to an issue with JSON: undefined.jpg not found

I'm struggling to concatenate my image names in this JavaScript code as a newbie, especially since it's pulling from JSON. Any assistance would be greatly appreciated! Below is the JS code snippet I'm working with: function log(msg){ ...

The JSON on the Express page only appears after refreshing the page

When accessing my page at /id, the data pulled from an external API using Express does not display until the page is refreshed. Any suggestions on how to solve this issue? // Retrieves basic account data router.get('/:id', function(req, res, nex ...

Building a Custom Component in Laravel Spark

I'm attempting to integrate my custom component into my Laravel Spark environment, but I keep encountering the following error: Property or method "obj" is not defined on the instance but referenced during render. Everything works perfectly when I ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

`Need to clean parameters for safe use in JavaScript code?`

I am working with the php code below: <?php $redirect_lp = $_GET['lp']; ?> <script> setTimeout(function(){ window.location.href = "<?php echo $redirect_lp; ?>"; }, 10) </script> How can I properly sanitiz ...

What is the mechanism through which createStore fetches the initialState from the reducer function in redux?

While analyzing the code of redux in createStore.js, I am having trouble understanding how it retrieves the initial state from the reducer function when it is specified as the 1st argument. https://github.com/reduxjs/redux/blob/master/src/createStore.js#L ...

What is the correct way to utilize href in CSS content property?

Below is the content of a box I have: https://i.sstatic.net/QmG5i.png When the above box is hovered over, it flips to this: https://i.sstatic.net/QsS9t.png This block's HTML code is as follows: <div class='tiles'> <div class= ...

Attempting to bundle js files using Browserify, but encountering issues with require('jquery-datetimepicker') not functioning correctly

For bundling my javascript file, I rely on gulp + browserify. I start by running npm install select2 --save require("select2"); module.exports = { init: function() { $('#datetime-start').datetimepicker({ dayOfWeekStart : ...

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...