带有数据的 POST 请求的 Access-Control-Allow-Origin 错误

问题描述 投票:0回答:1

当服务器端是 ASP classic 并且客户端是使用类型脚本的 React 时,我尝试使用 Axios 创建带有数据的 post ajax 请求

这是我的服务器端:

<% Response.AddHeader "Access-Control-Allow-Origin", "*" %>
<% Response.AddHeader "Access-Control-Allow-Methods", "GET, POST, OPTIONS" %>
<% Response.AddHeader "Access-Control-Allow-Headers", "Content-Type, Authorization" %>



<%
    Response.Write("hed")

%>

这是我的简单客户端:

import React, { useState } from 'react';
import axios from 'axios';
import {loginResult} from './models/loginResult.ts'
const Login: React.FC = () => {
  const [username, setUsername] = useState('');

  const handleLogin = async () => {
    try {
        //const response = await axios.get('http://localhost:12403/login.asp');


        const dataToSend = {
            username: username,
        };
        const response = await axios.post('http://localhost:12403/login.asp',dataToSend);
        console.log(response.data);
        
        //var d = new loginResult();
        //d = JSON.parse(response.data);
        //console.log(d);
    } catch (error) {
        console.log(error);
    } finally {

    }
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
    
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;

我的索引.tsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Login from './Login.tsx';
const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <Login />
  </React.StrictMode>
);

这就是我根据我的要求得到的:

当我在没有数据的情况下尝试它时:

const response = await axios.post('http://localhost:12403/login.asp');
它工作正常 像那样 :

axios asp-classic react-typescript access-control react-tsx
1个回答
0
投票

您还需要在服务器端文件中的“AddHeader”行末尾添加它:

<% Response.AddHeader "Access-Control-Allow-Credentials", "true" %>

如果没有解决,保留它并将“*”更改为本地主机:

<% Response.AddHeader "Access-Control-Allow-Origin", "http://localhost" %>

或者也添加端口:

<% Response.AddHeader "Access-Control-Allow-Origin", "http://localhost:3000" %>

© www.soinside.com 2019 - 2024. All rights reserved.