Can't access body data from fetch PUT to express server

为君一笑 提交于 2020-01-06 03:13:08

问题


I'm fairly new to web development and I'm trying to send some JSON data to a node.js server running express but I'm getting this error:

Failed to load http://localhost:8888/: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

I have no idea what this means. This is the client-side fetch:

fetch('http://localhost:8888/', {
        method: 'PUT',
        body: JSON.stringify(this.exercises),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => res.json())
    .catch(err => console.error('Error: ' + err))
    .then(res => console.log('Success: ' + res));

And this is the server-side code:

app.put('/', (req, res, next) => {
    console.log('PUT request received');
    console.log(req.body);
});

The server doesn't even seem to receive the request. How do I make this work? Thanks in advance.


回答1:


Make sure to use bodyParser (to get access to the data we have to use body-parser, it allows express to read the body). npm install --save body-parser

const bodyParser = require('body-parser');

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

Set up cors

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});
  }
  next();
});

Make sure that you define the configurations beforedefining routes. Info about cors: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS



来源:https://stackoverflow.com/questions/51231946/cant-access-body-data-from-fetch-put-to-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!