简体   繁体   English

如何从 Express 后端服务器发送和获取数据

[英]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每次我尝试运行此代码时,我都会收到错误: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").语法错误返回的标记“h”指的是您发送的字符串的第一个字母(“helo”)。 If you want to decode json by using res.json(), you should also be sending json in your response.如果您想使用 res.json() 解码 json,您还应该在响应中发送 json。 Otherwise, you have to use another decoding method in React as res.text().否则,你必须在 React 中使用另一种解码方法 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 .对于 React 部分,您可以在此处查看有关如何解码响应的官方 Fetch 文档。

You need to console.log(await res.json())你需要 console.log(await res.json())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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