簡體   English   中英

處理 Http 請求

[英]Handling Http requests

我對后端開發和將前端集成到后端非常陌生。 我的問題是,在嘗試發送發布請求時,我得到一個 404 狀態代碼POST http://localhost:5000/api/data 404 (Not Found)我前端的代碼是:

useEffect(() => {
    fetch('http://localhost:5000/api/data')
    .then(res => { return res.json() })
    .then((data) => {
      setData(data)
      setDatarecieved(true)
    })
  }, [])


  const clickHandler = () => {
    fetch('http://localhost:5000/api/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          "id": 5,
          "name":"test"
        })
      })
    }

請注意,它的第一部分完美無缺。 我的問題僅限於 post req。

我后端的代碼如下:

const express=require('express');
const app=express();
const data = require('./data.json');

const cors=require("cors");
const corsOptions ={
   origin:'*',
   credentials:true,
   optionSuccessStatus:200,
}

app.use(cors(corsOptions)) 

app.get('/',(req,res)=>{
    res.send('Hello World');
});

app.get('/api/data',(req,res)=>{
    res.send(data);
});

app.get('/api/data/:id',(req,res)=>{
    const x=data[req.params.id];
    res.send(data);
});

app.listen(5000,()=>{
    console.log('Server is running on port 5000');
});

提前致謝

老板,你好像在找這個

 app.post('/api/data',(req,res)=>{
    console.log(req.body)
        res.send(req.body);
    });

您的后端沒有 post 方法的路線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM