Javascript 我能';t通过POST请求从我的节点服务器访问数据

Javascript 我能';t通过POST请求从我的节点服务器访问数据,javascript,node.js,rest,async-await,fetch,Javascript,Node.js,Rest,Async Await,Fetch,我用express、body parser和cors三个包制作了一个节点服务器。 我正在尝试使用一个异步/等待函数从app.js中的客户端访问数据,该函数有一个post请求,其中包含我想要获取的所需数据 这是app.js中的fetch请求和post请求,我正试图通过app.js中的postData函数传递数据[温度、日期、用户响应]: //post routes const postData=async function postData(url = 'http://api.ope

我用express、body parser和cors三个包制作了一个节点服务器。 我正在尝试使用一个异步/等待函数从app.js中的客户端访问数据,该函数有一个post请求,其中包含我想要获取的所需数据

这是app.js中的fetch请求和post请求,我正试图通过app.js中的postData函数传递数据[温度、日期、用户响应]:

    //post routes
   const postData=async function postData(url = 'http://api.openweathermap.org/data/2.5/weather?zip=', data = {}) {
    
    const response = await fetch(url, {
      method: 'POST', 
      mode: 'cors',
      cache: 'no-cache', 
      credentials: 'same-origin', 
      headers: {
        'Content-Type': 'application/json'
        
      },
      redirect: 'follow',
      referrerPolicy: 'no-referrer',
      body: JSON.stringify(data) 
    });
    return await response.json();
}
  
postData('/add', {temperature: '1', date: '2', userResponse: '2'});
}
下面是服务器端代码,我在其中添加了一个路由作为post路由:

// Setup empty JS object to act as endpoint for all routes
projectData = {};

// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
const port = 3000;


// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);

function sendData (request, response) {
  response.send(projectData);
};

// TODO-ROUTES!
const data=[]

app.post('/add', function(req,res){
  data.push(req.body)
console.log(data)
})
下面是我在localhost:3000上运行项目时得到的信息

我希望参数温度、日期和用户响应显示在控制台中 第35行与post请求相关的错误如下:

app.js:35 POSThttp://localhost:3000/add net::ERR\u EMPTY\u响应 app.js:48未捕获(承诺中)类型错误:无法获取

不要介意上面两行与get请求相关的错误

在vs代码中,我可以看到这一点(温度、日期和用户响应显示在终端中,但不显示在浏览器的localhost:3000控制台中):


我只需要客户端将数据动态地传递到服务器端,而不只是在服务器端传递响应,您不会从服务器发回任何响应。发送一些响应,如下所示

app.post('/add', function(req,res){
  data.push(req.body)
  console.log(data)
  return res.send({}); //return whatever response you need to send
})

你需要回应这个请求。在
app.post('/add'
中使用例如
res.json({success:true})
我认为
无法获取
错误是由于超时而引发的,因为您没有响应。您的问题是什么?如@Molda所述,您应该响应您的POST请求。是吗?@Molda确定错误消失了,但我看不到表中的温度和其他数据console@Pavlo我需要console.log数据数组控制台数据不是来自客户端吗?我需要在项目中这样做,请检查客户端代码哪些数据?我可以看到你已经在这里传递数据“body:JSON.stringify(data)”你能在客户端看到postData函数吗?我传递了温度、日期、用户响应