【问题标题】:Can't access body data from fetch PUT to express server无法从 fetch PUT 访问正文数据到 express 服务器
【发布时间】:2018-07-08 20:56:25
【问题描述】:

我是 Web 开发的新手,我正在尝试将一些 JSON 数据发送到运行 express 的 node.js 服务器,但我收到了这个错误:

无法加载http://localhost:8888/:方法 PUT 不允许 预检响应中的 Access-Control-Allow-Methods。

我不知道这意味着什么。这是客户端获取:

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));

这是服务器端代码:

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

服务器似乎甚至没有收到请求。我该如何进行这项工作?提前致谢。

【问题讨论】:

  • 您的服务器没有响应任何数据。所以你的客户会一直挂在那里直到超时。尝试在最后一个 console.log 之前添加 res.send('');。

标签: javascript node.js express fetch


【解决方案1】:

确保使用 bodyParser(要访问我们必须使用 body-parser 的数据,它允许 express 读取正文)。 npm install --save body-parser

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

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

设置关联

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();
});

确保在定义路由之前定义配置。 cors相关信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

【讨论】:

猜你喜欢
  • 2020-05-31
  • 2018-08-21
  • 2018-05-26
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 2019-02-02
  • 2021-05-27
  • 1970-01-01
相关资源
最近更新 更多