在React JS中调用axios获取请求时出现网络错误

时间:2019-05-24 17:50:46

标签: reactjs axios

我在Mac OS中使用React.js,当我尝试调用axios.get时,出现网络错误。我读过许多其他案例,例如我的我正在使用react native的情况,他们的答案是添加设置以允许他们在mac中使用http而不是https,但是该设置不能在react js中使用。

任何建议将不胜感激。

错误:网络错误     在createError(createError.js:17)     在XMLHttpRequest.handleError(xhr.js:87)

我的代码是这样的:

pub fn cities(
    _req: HttpRequest,
    info: web::Path<(String,)>,
    data: web::Data<Arc<Mutex<DbData>>>,
) -> impl Responder {
    let letters = &info.0;
    println!("{}", letters);
    let mut re = String::with_capacity(4 + letters.len());
    re += "(?i)";
    re += letters;
    let re = Regex::new(&re).unwrap();

    let db_data = data.lock().unwrap();

    let cities: Vec<City> = db_data
        .cities
        .iter()
        .filter(|c| re.is_match(&c.name))
        .map(|c| c.clone())
        .collect();

    web::Json(cities)
}

5 个答案:

答案 0 :(得分:1)

即使将await置于await状态,也可以将await更改为诺言。

async functionName() {
  let response = () => {
    return new Promise(function(resolve, reject) {
      fetch('http://xxxxx/WebServiceTest/service.svc?wsdl/GetItems', {
        params: {
          Number: "100",
          Id: "101",
          userName: "11",
          credential: "Test"
        }
      }).then(response => {
        resolve(response);
      });
    });
  };
  let responseData = await response();
  console.log(responseData.data);
}

答案 1 :(得分:1)

您可以在服务器端代码上使用一些命令在reactjs中使用axios方法来摆脱cors策略错误 我已经在php的服务器端代码中使用了这些命令

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ll;
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define INF 0x3f3f3f3f3f

ll dist(ll x1 , ll x2 , ll y1 , ll y2){

    ll x = (x1-x2)*(x1-x2);
    ll y = (y1-y2)*(y1-y2);

    return ( x+y );
}

int main() {

    fastio;

    ll n,m;
    ll a[1005][2];
    ll b[1005][2];
    ll dp[1005][1005][2];

    cin >> n >> m;
    for(ll i = 1; i <= n; i++) cin >> a[i][0] >> a[i][1];
    for(ll i = 1; i <= m; i++) cin >> b[i][0] >> b[i][1];



    for(ll i = 0; i <= n; i++) {
        for (ll j = 0; j <= m; j++) {
            dp[i][j][0] = INF;
            dp[i][j][1] = INF;
        }
    }

    dp[0][0][0] = 0;
    dp[0][0][1] = 0;
    dp[1][0][0] = 0;

    for(ll i = 1; i <= n; i++){
        for(ll j = 0; j <= m; j++){

            // dp[i][j][0] :
            if(i > 1) dp[i][j][0] = min(dp[i][j][0] , dp[i-1][j][0] + dist(a[i-1][0] , a[i][0] , a[i-1][1] , a[i][1]));
            if(i > 1 && j >= 1 ) dp[i][j][0] = min(dp[i][j][0] , dp[i-1][j][1] + dist(b[j-1][0] , a[i][0] , b[j-1][1] , a[i][1]));

            // dp[i][j][1] :

            if(j > 1 ) dp[i][j][1] = min(dp[i][j][1] , dp[i][j-1][0] + dist(a[j-1][0] , b[j][0] , a[j-1][1] , b[j][1]));
            if(j > 1 ) dp[i][j][1] = min(dp[i][j][1] , dp[i][j-1][1] + dist(b[j-1][0] , b[j][0] , b[j-1][1] , b[j][1]));

        }
    }

    cout << dp[n-1][m-1][0];

    return 0;
}

记住:立即在会话开始时添加这些行

答案 2 :(得分:0)

我已经通过使用@CrossOrigin注释在Spring Boot中找到了解决方案。

@RestController
@CrossOrigin
@RequestMapping("/cus")
public class CusController{

    @Autowired
    CustomerService cus_service=null;

    @PostMapping("/save")
    public Customer saveCustomer(@RequestBody Customer customer)
    {

        if(customer!=null)
            return cus_service.saveCustomer(customer);
        else
            throw new DataNotFoundException("Data Not Available For Customer");

    }
}


答案 3 :(得分:0)

您可以简单地在您的

中进行以下更改
axios.create({baseURL:" "});

放入

const instance = axios.create(
{
        baseURL: "",
        withCredentials: false,
        headers: {
          'Access-Control-Allow-Origin' : '*',
          'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',   
      }
  })

在您需要创建axios实例的任何地方,尝试添加以上内容。如果您使用的是默认axios,则考虑按照上述代码创建自定义实例。

答案 4 :(得分:0)

  1. 我们必须允许 CORS,在请求头中放置 Access-Control-Allow-Origin:* 可能不起作用。安装启用 CORS 请求的 google 扩展程序。

  2. 确保您在请求中提供的凭据有效。

  3. 如果您将请求传递给虚拟宅基地服务器,请确保机器已配置。如果您使用 vagrant 尝试 vagrant up --provision 这将使本地主机连接到宅基地的数据库。

  4. 尝试更改标题的内容类型。 header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' } 这一点很重要。