You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5中无法获取GET请求响应问题求助

Troubleshooting Angular 5 + WP REST API Nonce Retrieval Issue

Hey there, let's work through your problem step by step. The "Http failure response for (unknown url): 0 Unknown Error" you're seeing is a common cross-origin request issue, and there are a few code tweaks we need to make too.

1. Fix the CORS (Cross-Origin Resource Sharing) Issue

Postman doesn't enforce browser same-origin policy, which is why your request works there but fails in Angular. Here are three reliable fixes:

Option 1: Add CORS Headers Directly in WordPress

Add this code to your WordPress theme's functions.php file to allow cross-origin requests from your Angular app:

add_action('rest_api_init', function () {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function ($value) {
        // Replace * with your Angular app's URL in production (e.g., http://localhost:4200)
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');
        return $value;
    });
});

Option 2: Use an Angular Proxy Configuration

Create a proxy.conf.json file in your Angular project root:

{
  "/b0ffv3BH7K6h/*": {
    "target": "http://localhost",
    "secure": false,
    "changeOrigin": true
  }
}

Then start your Angular app with the proxy enabled:

ng serve --proxy-config proxy.conf.json

This routes your Angular requests through the proxy, bypassing browser CORS restrictions.

Option 3: Install a WordPress CORS Plugin

Plugins like WP REST API CORS or Enable CORS can handle header setup automatically if you prefer a no-code approach.

2. Fix Asynchronous Code Order

Your console.log(this.nonce) runs before the API request completes (since Observables are asynchronous). Move that log inside the subscribe callback to see the actual nonce value:

getNonce(){
  console.log('getNonce()');
  this.authService.getNonce()
    .subscribe( data => {
      // No need for JSON.stringify - HttpClient already parses the response to an object
      this.nonce = data.nonce; 
      console.log('Received nonce:', this.nonce); // This will log the correct value
    }, (error)=>{
      this.onError(error);
      console.log(error);
    } );
  // This log runs before the API call finishes - remove or move it inside the callback
  // console.log(this.nonce); 
}

Also, update your ApiConfigNonce interface to use lowercase string (standard TypeScript convention):

export interface ApiConfigNonce { 
  status: string; 
  controller: string; 
  method: string; 
  nonce: string; 
}

3. Fix URL Spacing Error

In your auth.service.ts newUser method, there's an extra space in the URL (/? username=). Remove that space to avoid invalid request URLs:

newUser(username, email, password, firstname, lastname, nonce){
  return this.http.get(this.apiHost + this.apiBase + 'user/register/?username='+ username + '&email=' + email + '&nonce=' + nonce + '&first_name=' + firstname + '&last_name=' + lastname);
}

4. Improve Error Handling

Update your onError method to specifically handle the CORS error (status 0) and log full error details for easier debugging:

onError(response){
  console.log('Full error details:', response); // This helps diagnose hidden issues
  if(response.status === 0){
    this.errorMessage = "CORS error detected - please check your WordPress server's CORS settings";
  } else {
    switch (response.error.code) {
      case 406:
        this.errorMessage = "Either that email or username is already in use";
        break;
      case 403:
        this.errorMessage = "Failed to authorize, please try again later";
        break;
      default:
        this.errorMessage = "There was an error signing you up, please try again";
        break;
    }
  }
  this.busyProcessing = false;
}

Start with fixing the CORS issue first, as that's the most likely cause of the "0 Unknown Error". Then apply the other tweaks, and your nonce should start loading correctly.

内容的提问来源于stack exchange,提问作者Shaun Reddiar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:02:56