【问题标题】:Express server blocking form/data from chrome client even with cors middleware applied [duplicate]即使应用了cors中间件,Express服务器也会阻止来自chrome客户端的表单/数据[重复]
【发布时间】:2021-03-13 15:43:49
【问题描述】:

我有一个连接到 MongoDB 的快速服务器。这里的 url 是 localhost:1337,我有一个路由 localhost:1337/api/user/avatar,我想将图像文件发布到,以在用户对象上存储头像。 npm 包 cors 已正确设置为中间件。

当我使用 Postman 测试 REST 端点时,它工作正常。但是当我尝试使用以下上传组件(从 chrome 构建和运行)时,我在 Chrome 控制台中收到此错误:

上传:1 从源“http://localhost:3000”访问“localhost:1337/api/user/avatar/5fc520239005616f09fb7d86”的 XMLHttpRequest 已被 CORS 策略阻止:仅支持跨源请求对于协议方案:http、data、chrome、chrome-extension、chrome-untrusted、https。

import React, { useState, useEffect } from "react"
import ImageUploading from "react-images-uploading"
import base64js from 'base64-js'
import axios from 'axios'
import backend from '../../api'

const Upload = ({userId}) => {

  const [images, setImages] = useState([])
  const maxNumber = 69

  useEffect(() => {
    // axios.post("./")
        if (images[0]) {
          var bodyFormData = new FormData();
          bodyFormData.append('avatar', images[0].file);
          console.log(bodyFormData)
          axios({
            method: 'post',
            url: `localhost:1337/api/user/avatar/${userId}`,
            data: bodyFormData,
            headers: {'Content-Type': 'multipart/form-data' }
            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (response) {
                console.log(response);
            });
        }
      return () => {
          // cleanup
     }
  }, [images])

  const onChange = (imageList, addUpdateIndex) => {
    // data for submit
    console.log(imageList, addUpdateIndex)
    // Function which adds the image to the database goes here.
    setImages(imageList)
  }

  return (
    <div className="Upload">
      <ImageUploading
        multiple
        value={images}
        onChange={onChange}
        maxNumber={maxNumber}
        dataURLKey="data_url"
      >
        {({
          imageList,
          onImageUpload,
          onImageRemoveAll,
          onImageUpdate,
          onImageRemove,
          isDragging,
          dragProps,
        }) => (
          // write your building UI
          <div className="upload__image-wrapper">
            <button
              style={isDragging ? { color: "red" } : null}
              onClick={onImageUpload}
              {...dragProps}
            >
              Click or Drop here
            </button>
            &nbsp;
            <button onClick={onImageRemoveAll}>Remove all images</button>
            {imageList.map((image, index) => (
              <div key={index} className="image-item">
                <img src={image.data_url} alt="" width="100" />
                <div className="image-item__btn-wrapper">
                  <button onClick={() => onImageUpdate(index)}>Update</button>
                  <button onClick={() => onImageRemove(index)}>Remove</button>
                </div>
              </div>
            ))}
          </div>
        )}
      </ImageUploading>
    </div>
  )
}

export default Upload

【问题讨论】:

  • 你是否在 postman 中测试通过 localhost:3000 发送数据?
  • 无论哪种方式,您可能都必须从 axios 帖子中提供 cors 标头信息,并且服务器也必须接受它。

标签: javascript node.js reactjs express cors


【解决方案1】:

本地主机 URL 缺少 http://,从而导致错误。我以为我已经检查过了,但显然没有。

工作代码sn-p:

  useEffect(() => {
        if (images[0]) {
          var bodyFormData = new FormData();
          bodyFormData.append('avatar', images[0].file);
          console.log(bodyFormData)
          axios({
            method: 'post',
            url: `http://localhost:1337/api/user/avatar/${userId}`,
            data: bodyFormData,
            headers: {'Content-Type': 'multipart/form-data' }
            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (response) {
                console.log(response);
            })
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-30
    • 2015-05-05
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多