简体   繁体   中英

how to send and fetch data from an express backend server

this is my front end

export default async function get(){
    let res = await fetch('http://localhost:4000/data/');
    console.log(res.json());
}

and this is my backend

const scraper = require('./scraper.js');
const express = require('express');
const app = express();

app.get('/data', (req,res)=>{
    //let img = await scraper.search(req.query.item);
    res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.send("helo");
})

app.listen(4000);

everytime i try to run this code i get the error: syntaxerror: unexpected token h in json at position 0

should be a really simple task but for some reason it just doesnt want to work.. thanks in advance!

The token "h" that the syntax error returns refers to the first letter of the string you are sending ("helo"). If you want to decode json by using res.json(), you should also be sending json in your response. Otherwise, you have to use another decoding method in React as res.text().

Take a look at the express docs here to make sure, you are sending the correct information/format.

For the React part, you can check the official Fetch docs on how to decode the response here .

You need to console.log(await res.json())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM