REST API不允许来自本地主机的GET请求(axios)

vmdwslir  于 2022-11-23  发布在  iOS
关注(0)|答案(2)|浏览(170)

我一直在尝试通过Axios从REST API获得响应,我尝试设置标头,特别是错误消息中所述的Access-Control-Allow-Origin标头,这似乎是主要问题,因为即使我插入所需的标头,它仍然不确认标头。

axios
   .get(url, {
     headers: {
       "Access-Control-Allow-Origin": "*",
       crossDomain: true,
       "Content-Type": "text/plain;charset=utf-8",
     },
     params: {
       access_key: API_KEY,
       adults: adults,
       origin: origin,
       destination: destination,
       departure: departure,
     },
   })
   .then((res) => {
     console.log(res.data);
   });
zrfyljdw

zrfyljdw1#

CORS在后端配置,这里有一个NodeJS后端和ReactJS前端的示例。

//API
import express from "express";
const app = express();
import cors from "cors";

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
  cors({
    origin: [
      "http://localhost:3000",
    ],
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
    credentials: true,
  })
);

//React Frontend with useEffect and useState
useEffect(() => {
    const config = {
      headers: { "x-auth-token": token },
    };

    const fetchData = async () => {
      const results = await axios.get("/users/table", config);
      setRows(results.data);
    };
    fetchData();
  }, [setRows, state, token]);
7fhtutme

7fhtutme2#

Access-Control-Allow-Origin必须在后端设置,而不是在前端。例如,在PHP中,您可以在文件的开头设置头:

header('Access-Control-Allow-Origin: *');

然后在您的前端,以您通常的方式发送数据。此解决方案仅适用于能够访问您所查询的服务器后端的用户。

相关问题