Узловой сервер только принимает запросы GET, но не выполняет запросы POST - PullRequest
0 голосов
/ 24 января 2020

Я могу отправлять запросы GET на маршрут моего локального сервера / страницы. Но ничего не происходит при выполнении запросов POST из моего запроса на выборку на стороне клиента.

Вот мой запрос на выборку, данные находятся внутри объекта данных. Который я пытаюсь показать на стороне сервера.

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: 'no-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>
        )
      }
    }

Вот мой сервер узлов, на котором я пытаюсь прослушивать почтовые запросы, вот где я пытаюсь получить данные console.logged:

    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(express.static('public'))

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
       extended: false
    }));

    app.use(passport.initialize())
    passportInit()

    // Accept requests from our client
    app.use(cors({
      origin: CLIENT_ORIGIN
    }))


    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('?')) 

    // Direct other requests to the auth router
    app.use('/', authRouter)

    const handler = (req, res)=> {
      res.setHeader('Content-Type', 'application/json');
      res.send(req.body');
console.log(req.body)
    };

    app.post('/page', handler);



    server.listen(process.env.PORT || 8080, () => { //calllback function
      console.log('listening...')
    })

Вот мой пакет. json file:

  {
  "name": "social-auth-server",
  "version": "0.0.1",
  "description": "Server for React/Node Social auth",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js",
    "start": "node server"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.4",
    "dotenv": "^5.0.1",
    "express": "^4.16.3",
    "express-session": "^1.15.6",
    "https": "^1.0.0",
    "multer": "^1.4.2",
    "node-fetch": "^2.6.0",
    "passport": "^0.4.0",
    "passport-facebook": "^2.1.1",
    "passport-github": "^1.1.0",
    "passport-google-oauth": "^1.0.0",
    "passport-twitter": "^1.0.4",
    "path": "^0.12.7",
    "querystring": "^0.2.0",
    "readline": "^1.3.0",
    "request": "^2.88.0",
    "request-promise": "^4.2.2",
    "socket.io": "^2.1.1",
    "stream": "0.0.2"
  },
  "author": "funador",
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

В google chrome console.log для моего сервера показывает, что метод запроса GET, я думаю, он должен сказать POST также или просто POST один, что, как я думаю, проблема. console.log image

const express = require('express')
const router = express.Router()
const passport = require('passport')
const authController = require('./auth.controller')

// Setting up the passport middleware for each of the OAuth providers
const twitterAuth = passport.authenticate('twitter')
const googleAuth = passport.authenticate('google', { scope: ['profile'] })
const facebookAuth = passport.authenticate('facebook')
const githubAuth = passport.authenticate('github')

// Routes that are triggered by the callbacks from each OAuth provider once
// the user has authenticated successfully


router.get('/google/callback', googleAuth, authController.google)
router.get('/facebook/callback', facebookAuth, authController.facebook)
router.get('/github/callback', githubAuth, authController.github)

// This custom middleware allows us to attach the socket id to the session

router.use((req, res, next) => {
  req.session.socketId = req.query.socketId
  next()
})

// Routes that are triggered on the client //
router.get('/twitter', twitterAuth)
router.get('/google', googleAuth)
router.get('/facebook', facebookAuth)
router.get('/github', githubAuth)



module.exports = router
...