最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get returned string values in fetch() - Stack Overflow

programmeradmin9浏览0评论

Below code is my fetch method in my separate register.js. This is my newly created js file, so I can create my front end. At the moment I'm just trying to console.log the ending result for this fetch, but can't get the output since I'm getting an error when I try to POST this.

error in browser console: "Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0"

        fetch(`${rootUrl}api/users/register`,{

        method:"POST",
        headers:{
            "Content-Type": "application/json"
        },
        body:JSON.stringify({
            
                firstName: firstName,
                lastName: lastName,
                mobileNo: mobileNo,
                email: email,
                password: password
        })

    })
    .then(result=>result.json())
    .then(result =>{

        console.log(result);
    

    })

In userRouter.js, this is the route I'm fetching in register.js above:

router.post('/register', (req, res)=>{

userController.register(req.body).then(result => res.send(result))})

And the route leads to this controller in Usercontroller.js:

module.exports.register = (reqBody)=>{

//check if email already exists before registering new user
return User.find({email: reqBody.email}).then((result, error) =>{

        if(result.length != 0){

            return "EMAIL EXISTS!";

        }else{

            let newUser = new User({

                firstName: reqBody.firstName,
                lastName: reqBody.lastName,
                email:reqBody.email,
                password: bcrypt.hashSync(reqBody.password, 10),
                mobileNo: reqBody.mobileNo

            })

                return newUser.save().then((result, error)=>{

                if (error){

                    return error;

                }else{

                    return "SUCCESFULLY REGISTERED NEW USER";
                }
            })

            
        }
    })}

As you can see, this is a registration form. Everything works fine in the backend, using postman to enter values. All my condition prompts are being returned(emails exist, successful registration).

But when I tried creating a frontend for it, I can't get my defined prompts.Like when I deliberately input a duplicate email, I can't get the message "Email exists" that I used to get when using only postman or just backend API functionality.

I feel like something is very wrong with what I'm trying to do. I'm having trouble creating a frontend for my API which I'm not used at the moment.

Below code is my fetch method in my separate register.js. This is my newly created js file, so I can create my front end. At the moment I'm just trying to console.log the ending result for this fetch, but can't get the output since I'm getting an error when I try to POST this.

error in browser console: "Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0"

        fetch(`${rootUrl}api/users/register`,{

        method:"POST",
        headers:{
            "Content-Type": "application/json"
        },
        body:JSON.stringify({
            
                firstName: firstName,
                lastName: lastName,
                mobileNo: mobileNo,
                email: email,
                password: password
        })

    })
    .then(result=>result.json())
    .then(result =>{

        console.log(result);
    

    })

In userRouter.js, this is the route I'm fetching in register.js above:

router.post('/register', (req, res)=>{

userController.register(req.body).then(result => res.send(result))})

And the route leads to this controller in Usercontroller.js:

module.exports.register = (reqBody)=>{

//check if email already exists before registering new user
return User.find({email: reqBody.email}).then((result, error) =>{

        if(result.length != 0){

            return "EMAIL EXISTS!";

        }else{

            let newUser = new User({

                firstName: reqBody.firstName,
                lastName: reqBody.lastName,
                email:reqBody.email,
                password: bcrypt.hashSync(reqBody.password, 10),
                mobileNo: reqBody.mobileNo

            })

                return newUser.save().then((result, error)=>{

                if (error){

                    return error;

                }else{

                    return "SUCCESFULLY REGISTERED NEW USER";
                }
            })

            
        }
    })}

As you can see, this is a registration form. Everything works fine in the backend, using postman to enter values. All my condition prompts are being returned(emails exist, successful registration).

But when I tried creating a frontend for it, I can't get my defined prompts.Like when I deliberately input a duplicate email, I can't get the message "Email exists" that I used to get when using only postman or just backend API functionality.

I feel like something is very wrong with what I'm trying to do. I'm having trouble creating a frontend for my API which I'm not used at the moment.

Share Improve this question asked Sep 8, 2021 at 5:33 quielfalaquielfala 5991 gold badge7 silver badges28 bronze badges 2
  • 3 you're not responding with JSON ... use result.text() instead of result.json() – Bravo Commented Sep 8, 2021 at 5:37
  • Oh, what a simply solution was that. I thought at first this has something to do with promises. Thanks – quielfala Commented Sep 8, 2021 at 5:59
Add a ment  | 

3 Answers 3

Reset to default 8

You are returning a non JSON response, so you can't use res.json(). You are simply sending a text response. So use res.text()

fetch('/your-endpoint').then((res)=>{
  return res.text();
}).then((text)=>{
 console.log(text)
})

There are some hints to be pointed out.

  • Check the rootUrl since after that there's no foreslash.

  • You're sending back the Text Style. use this instead to have the result json format.

    res.status(200).json({result})

  • Try not to use Synchronous Functionalities on the back side. You should give it a wide berth, or rather, use bcrypt.hash() mixed with Async Function to remove the CallBack Function until it gets done. What's more, so as to check the previous function's error to get it on the front side using Fetch / Axios. use Try/Catch method.

  • I'd use axios [ axios.request({}) | axios.post(..)] if I were in your shoes.

I had a similar issue but i just needed to use GET method and not post. For people who are looking for an async await solution:

const response = await fetch("www.google.de");
const text = await response.text();
console.log(text);
发布评论

评论列表(0)

  1. 暂无评论