简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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