Javascript 无法从前端客户端向本地节点服务器发出fetch post请求,只能获取请求

Javascript 无法从前端客户端向本地节点服务器发出fetch post请求,只能获取请求,javascript,node.js,reactjs,fetch,Javascript,Node.js,Reactjs,Fetch,当向本地服务器(localhost:8080/页)发出post请求时,显示“无法获取/页”。我正在使用Google Chrome,其中“开发工具网络”选项卡显示: 下面是我的前端代码和简单的fetch语句: import React, { Component } from 'react' import io from 'socket.io-client' import OAuth from './OAuth' import Loading from './Loading' import Foot

当向本地服务器(localhost:8080/页)发出post请求时,显示“无法获取/页”。我正在使用Google Chrome,其中“开发工具网络”选项卡显示:

下面是我的前端代码和简单的fetch语句:

import React, { Component } from 'react'
import io from 'socket.io-client'
import OAuth from './OAuth'
import Loading from './Loading'
import Footer from './Footer'
import Tweets from './Tweets'
import { API_URL } from './config'
import './App.css'
const socket = io(API_URL) //,{transports: ['websocket']}
const providers = ['twitter', 'google', 'facebook', 'github']//import theese in because our auth controller needs to call our event for each provider which the event is named after the provider

export default class App extends Component {

  state = {
    loading: true
  }

  componentDidMount() {

    socket.on('connect', function(){
      console.log('connected')
    });

    fetch(`${API_URL}/wake-up`)
      .then(res => {
        if (res.ok) {
          this.setState({loading: false})
        }
      })

      const data = {
        random1: 'random',
        random2: 'random-input'
      }

      const options = {
          method:'POST',
          mode: 'cors',
          header: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
      }

        fetch(`${API_URL}/page`, options);
  }

  render() {
    const divStyles = {

    }
    const buttons = (providers, socket) =>
      providers.map(provider =>
        <OAuth
          provider={provider}
          key={provider}
          socket={socket}
        />
      )

    return (
      <div className='wrapper'>
        <div className='container'>
          {this.state.loading
            ? <Loading />
            : buttons(providers, socket)
          }
        </div>
{
buttons
? <Tweets provider='twitter' />
: <div> Hasnt fetched</div>
}
        <Footer />
      </div>
    )
  }
}
import React,{Component}来自“React”
从“socket.io客户端”导入io
从“/OAuth”导入OAuth
从“./Loading”导入加载
从“./Footer”导入页脚
从“./Tweets”导入推文
从“/config”导入{API_URL}
导入“./App.css”
const socket=io(API_URL)/,{transports:['websocket']}
const providers=['twitter'、'google'、'facebook'、'github']//导入此事件,因为我们的身份验证控制器需要为每个以提供程序命名的提供程序调用我们的事件
导出默认类应用程序扩展组件{
状态={
加载:正确
}
componentDidMount(){
socket.on('connect',function(){
console.log('已连接')
});
获取(`${API\u URL}/wake-up`)
。然后(res=>{
如果(res.ok){
this.setState({loading:false})
}
})
常数数据={
随机1:'随机',
随机2:“随机输入”
}
常量选项={
方法:'POST',
模式:“cors”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(数据)
}
获取(`${API\u URL}/page`,选项);
}
render(){
常量divStyles={
}
常量按钮=(提供程序、套接字)=>
providers.map(provider=>
)
返回(
{this.state.loading
? 
:按钮(提供程序、套接字)
}
{
按钮
? 
:尚未提取
}
)
}
}
这是我的后端节点服务器(server.js),我有app.post可用,但仍然没有结果,我在下面附上了我的路由文件:

        require('dotenv').config()
    const express = require('express')
    const path = require('path')
    const fs = require('fs')
    const https = require('https')
    const http = require('http')
    const passport = require('passport')
    const session = require('express-session')
    const cors = require('cors')
    const socketio = require('socket.io')
    const authRouter = require('./lib/auth.router')
    const passportInit = require('./lib/passport.init')
    const { SESSION_SECRET, CLIENT_ORIGIN } = require('./config')
    const bodyParser = require('body-parser')
    const app = express()
    let server


    // If we are in production we are already running in https
    if (process.env.NODE_ENV === 'production') {
      server = http.createServer(app)
    }
    // We are not in production so load up our certificates to be able to
    // run the server in https mode locally
    else {
      const certOptions = {
        key: fs.readFileSync(path.resolve('./certs/server.key')),
        cert: fs.readFileSync(path.resolve('./certs/server.crt'))
      }
      server = https.createServer(certOptions, app)
    }

    // Setup for passport and to accept JSON objects


    app.use(express.json())
    app.use(bodyParser.json());
    app.use(passport.initialize())
    passportInit()

    // Accept requests from our client
    app.use(cors())

    // saveUninitialized: true allows us to attach the socket id to the session
    // before we have athenticated the user
    app.use(session({
      secret: process.env.SESSION_SECRET,
      resave: true,
      saveUninitialized: true
    }))

    // Connecting sockets to the server and adding them to the request
    // so that we can access them later in the controller
    const io = socketio(server)
    app.set('io', io)

    // Catch a start up request so that a sleepy Heroku instance can
    // be responsive as soon as possible

    app.get('/wake-up', (req, res) => res.send('You need to define your route for both get and post if you want to be able to reach it with both verbs. You could do something like this:

const handler = (req, res)=> {
  res.setHeader('Content-Type', 'application/json');
  res.send('yes');
};
app.get('/page', handler);
app.post('/page', handler);
require('dotenv').config()
const express=require('express')
const path=require('路径')
常量fs=require('fs')
常量https=require('https')
const http=require('http')
const passport=require(‘passport’)
const session=require('express-session')
const cors=require('cors')
const socketio=require('socket.io')
const authRouter=require('./lib/auth.router')
const passportInit=require('./lib/passport.init')
const{SESSION\u SECRET,CLIENT\u ORIGIN}=require(“./config”)
const bodyParser=require('body-parser')
const app=express()
让服务器
//如果我们在生产中,我们已经在https中运行了
if(process.env.NODE_env===‘生产’){
server=http.createServer(应用程序)
}
//我们不在生产中,所以请加载我们的证书以便能够
//在本地以https模式运行服务器
否则{
常数证书选项={
key:fs.readFileSync(path.resolve(“./certs/server.key”),
cert:fs.readFileSync(path.resolve('./certs/server.crt'))
}
服务器=https.createServer(证书选项,应用程序)
}
//passport和接受JSON对象的设置
app.use(express.json())
use(bodyParser.json());
app.use(passport.initialize())
passportInit()
//接受客户的请求
app.use(cors())
//saveUninitialized:true允许我们将套接字id附加到会话
//在我们确定用户之前
应用程序使用(会话)({
机密:process.env.SESSION\u secret,
雷萨夫:是的,
saveUninitialized:true
}))
//将套接字连接到服务器并将其添加到请求
//这样我们以后可以在控制器中访问它们
常量io=socketio(服务器)
应用程序集('io',io)
//捕获启动请求,以便休眠的Heroku实例可以
//尽快作出反应

app.get('/wake-up',(req,res)=>res.send('如果你想用这两个动词都能到达它,你需要为get和post定义路线。你可以这样做:


欢迎使用Stack Overflow!您定义了一个发布路径,但是您正在
获取
-ing页面,查看您的开发工具屏幕快照是的,谢谢,我意识到了,但我不确定如何从获取更改为发布。由于我希望将数据发布到该/page routeAnks以获得您的帮助,这是可行的,但我也希望能够发布从获取路径发送的数据app.js中的ost请求。你能再帮点忙吗?恐怕我不明白你到底想做什么。我正在尝试返回post请求,我意识到唯一被监听的方法是get请求,但post请求似乎不起作用。