繁体   English   中英

我没有得到 nodejs 服务器的响应。 它在向服务器请求后显示未定义

[英]I didn't get response from the nodejs server. It showing undefine after request to server

我在 Firebase 和 Heroku 等两个不同平台上托管网站
我有一些问题

  1. 首先,当我将数据从 firebase 托管的 URL 发布到 Heroku 上托管的服务器时,它显示 cors 错误
  2. 然后在解决 cors 错误后,数据无法来自服务器,它在控制台中显示未定义
    这是我在 Heroku 上托管的服务器端代码
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 3000
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())

app.use(express.json({limit:'1mb'}))

app.use(function (req, res, next) {

res.header('Access-Control-Allow-Origin', 'https://sample-377b8.web.app');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With,content-type,Accept,Authorization',);
res.header('Access-Control-Allow-Credentials', true);
if(req.method=="OPTIONS"){
  res.header('Access-Control-Allow-Methods','PUT,POST,DELETE,PATCH')
  return res.status(200).json({})
}
// Pass to next layer of middleware
next();
});
let data;
app.get('/',(req,res)=>{
res.send("hello world")
}) 
app.post('/',(req,res)=>{
 
  data = req.body
 console.log(data)
 res.status(200).json({
  "success":"200 response",
  "res":"You are now just talked with server" 
 })

})


app.listen(PORT, () => console.log(`Listening on ${ PORT }`))

这是我的客户端代码

document.getElementById('send').addEventListener('click',async()=>{
           let data = {lat,lon}
            await fetch('https://demoserver-app.herokuapp.com/',{mode:"no-cors"},{
            method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
           }).then( async (dat) =>{
             console.log(res.json())
           }).then(res =>{
               console.log(res)
           })
       })

它在控制台上给出错误,如控制台错误图像

网络标签页头信息 请求图片的头信息

我希望我能帮助你,我认为可以产生这种输出的一个问题是你 console.log(res) 但是 .then 指的是 (dat) 而且我认为你不需要在 .then(它已经是异步功能)试试这个:

 document.getElementById('send').addEventListener('click',async()=>{ let data = {lat,lon} await fetch('https://demoserver-app.herokuapp.com/',{mode:"no-cors"},{ method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }).then( data =>{ data.json() }).then(res =>{ console.log(res) }) })

好的,所以对于服务器端:1)您需要从 req.body 中解构数据,您所做的只是将 req.body 调整为数据栏。(请参阅我的解决方案)2)对于您需要创建目录的 post 方法而不是在根目录中尝试。 试试这个代码,你会看到你想要服务器的响应:

 app.post('/getmessage', (req,res) => { const {data} = req.body; console.log(data); res.status(200).json({ "success":"200 response", "res":"You are now just talked with server" }) })

客户:

 fetch('http://localhost:3000/getmessage', { method : 'post', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ data:"this is massage from client" }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.log(err))

暂无
暂无

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

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