javascript cors中间件不允许axios post的问题

eqfvzcg8  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(120)

我试图使用Tesseract.js库创建一个MERN应用程序,但Multer在我的帖子请求中遇到了问题。

Access to XMLHttpRequest at 'http://localhost:8000/receipts' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的server.js

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const dotenv = require("dotenv");
const receiptRoutes = require("./routes/receiptRoutes");

dotenv.config();
const app = express();

app.use("/receipts", receiptRoutes);
app.use(cors());
app.use(express.json({ extended: true }));

const PORT = process.env.PORT;
const CONNECTION_URL = process.env.CONNECTION_URL;

const connect = async () => {
  try {
    mongoose.connect(CONNECTION_URL);
    console.log("Established connnection to DB");
  } catch (error) {
    console.error(error);
  }
};

app.listen(PORT, () => {
  connect();
  console.log(`Server running on ${PORT}`);
});

我在react客户端上传jsx。在这里我试图提交我的文件,由mongoose db解析并上传到

import React, { useState } from "react";
import axios from "axios";

const ReceiptUpload = () => {
  const [file, setFile] = useState(null);
  const [processing, setProcessing] = useState(false);
  const [ocrResult, setOcrResult] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!file) return;

    setProcessing(true);
    const formData = new FormData();
    formData.append("receipt", file);

    try {
      const response = await axios.post(
        "http://localhost:8000/receipts",
        formData
      );
      setOcrResult(response.data.textData);
      setProcessing(false);
    } catch (error) {
      console.error(error);
      setProcessing(false);
    }
  };

  const handleChange = (e) => {
    setFile(e.target.files[0]);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="file" onChange={handleChange} />
        <button type="submit" disabled={!file || processing}>
          {processing ? "Processing..." : "Upload"}
        </button>
      </form>
      {ocrResult && (
        <div>
          <h2>OCR Result:</h2>
          <pre>{JSON.stringify(ocrResult, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default ReceiptUpload;

我试着允许origin像origin一样:“http://127.0.0.1:5173”但没有运气。

mqkwyuun

mqkwyuun1#

尝试将app.use(cors());移动到receipts路由的顶部。否则请求将永远不会到达cors中间件。

app.use(cors());
app.use("/receipts", receiptRoutes);

相关问题