GVKun编程网logo

反应代理错误:无法将请求/ api /从localhost:3000代理到http:// localhost:8000(ECONNREFUSED)

11

本篇文章给大家谈谈反应代理错误:无法将请求/api/从localhost:3000代理到http://localhost:8000,以及ECONNREFUSED的知识点,同时本文还将给你拓展angul

本篇文章给大家谈谈反应代理错误:无法将请求/ api /从localhost:3000代理到http:// localhost:8000,以及ECONNREFUSED的知识点,同时本文还将给你拓展angular – XHR错误(404 Not Found)加载http:// localhost:3000 / traceur、Angular2:应用程序启动时出错“http:// localhost:3000/traceur 404(找不到)”、API POST http://localhost:3000/[object%20Object]、ASP.Net:尝试处理http:// localhost:5957 / http://yahoo.com时出现HTTP 400 Bad Request错误等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

反应代理错误:无法将请求/ api /从localhost:3000代理到http:// localhost:8000(ECONNREFUSED)

反应代理错误:无法将请求/ api /从localhost:3000代理到http:// localhost:8000(ECONNREFUSED)

我有一个React前端,它使用jwt与Django后端进行身份验证。后端可以正常工作,并且使用django视图可以正常连接,但是当我尝试代理来自React的请求时,它给了我Connection
Refused错误。

代理错误:无法将请求/ api / auth / token / obtain /从localhost:3000代理到http://
localhost:8000(ECONNREFUSED)。

连接到http:// localhost:8000 / api / auth / token / obtain
/正常工作。使用Axios发送POST请求也可以正常工作,并返回令牌json。但是,当我用节点代理它时,它不起作用。

在我的package.json我有:

  "proxy": {    "/api/*":  {      "target": "http://localhost:8000"    }  },

编辑: 公共回购。如果安装了docker,则可以轻松运行。(使用1张图片和2个容器)。克隆后才运行docker-compose build,然后docker-compose up

Edit2:请求标头:

*General*Request URL: http://localhost:3000/api/auth/token/obtain/Request Method: POSTStatus Code: 500 Internal Server ErrorRemote Address: [::1]:3000Referrer Policy: no-referrer-when-downgrade*Response Headers*HTTP/1.1 500 Internal Server ErrorX-Powered-By: ExpressDate: Mon, 30 Apr 2018 21:23:17 GMTConnection: keep-aliveTransfer-Encoding: chunked*Request HeadersPOST /api/auth/token/obtain/ HTTP/1.1Host: localhost:3000Connection: keep-aliveContent-Length: 45Pragma: no-cacheCache-Control: no-cacheOrigin: http://localhost:3000User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36Content-Type: application/jsonAccept: */*Referer: http://localhost:3000/loginAccept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9,fr;q=0.8,ja;q=0.7

答案1

小编典典

因此,问题在于,由于Node dev环境和Django dev环境都在单独的docker容器中运行,因此localhost是指节点容器,而不是桥接网络。

因此,关键是要使用容器链接,当使用时会自动创建容器链接docker-compose,并将其用作主机名。所以我改成

"proxy": {    "/api":  {        "target": "http://django:8000"    }},

只要您使用相同的docker-compose命令启动两个容器,就可以了,否则,您必须在docker-compose.yml文件中手动指定external_links 。

angular – XHR错误(404 Not Found)加载http:// localhost:3000 / traceur

angular – XHR错误(404 Not Found)加载http:// localhost:3000 / traceur

当我在代码中尝试使用Angular Material时,我遇到了以下错误.
    zone.js:101 GET http://localhost:3000/traceur 404 (Not Found)scheduleTask @ zone.js:101ZoneDelegate.scheduleTask @ zone.js:345Zone.scheduleMacroTask @ zone.js:282(anonymous function) @ zone.js:122send @ VM437:3fetchTextFromURL @ system.src.js:1156(anonymous function) @ system.src.js:1739ZoneAwarePromise @ zone.js:607(anonymous function) @ system.src.js:1738(anonymous function) @ system.src.js:2764(anonymous function) @ system.src.js:3338(anonymous function) @ system.src.js:3605(anonymous function) @ system.src.js:3990(anonymous function) @ system.src.js:4453(anonymous function) @ system.src.js:4705(anonymous function) @ system.src.js:408ZoneDelegate.invoke @ zone.js:332Zone.run @ zone.js:225(anonymous function) @ zone.js:591ZoneDelegate.invokeTask @ zone.js:365Zone.runTask @ zone.js:265drainMicroTaskQueue @ zone.js:497ZoneTask.invoke @ zone.js:437
    login:15 Error: Error: XHR error (404 Not Found) loading http://localhost:3000/traceur
    at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:794:30)
    at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:365:38)
    at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:265:48)
    at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:433:34)
    Error loading http://localhost:3000/traceur
    Error loading http://localhost:3000/node_modules/@angular2-material/button/button.js as "@angular2-material/button" from http://localhost:3000/app/assets/js/app.module.js(anonymous function) @ login:15ZoneDelegate.invoke @ zone.js:332Zone.run @ zone.js:225(anonymous function) @ zone.js:591ZoneDelegate.invokeTask @ zone.js:365Zone.runTask @ zone.js:265drainMicroTaskQueue @ zone.js:497ZoneTask.invoke @ zone.js:437

以下是代码:
app.component.ts:

    import { Component,ViewEncapsulation } from '@angular/core';
    import { MdButton } from '@angular2-material/button';
    @Component({
    selector: 'myApp',templateUrl: './app/app.html',styleUrls: ['./app/app.css'],encapsulation: ViewEncapsulation.None
    })
    export class AppComponent {
    }

app.module.ts:

    import { NgModule } from '@angular/core';
    import { browserModule } from '@angular/platform-browser';
    import { FormsModule }   from '@angular/forms';
    import { HttpModule }    from '@angular/http';
    import { MdButtonModule } from '@angular2-material/button';
    import { routing,appRoutingProviders } from './app.routing';
    import { AppComponent } from './app.component';
    import { LoginModule } from './login/login.module';
    import { HomeModule } from './home/home.module';
    import { ItemsModule } from './items/items.module';
    import { MoviesModule } from './movies/movies.module';
    @NgModule({
    imports: [ browserModule,FormsModule,HttpModule,MdButtonModule,routing,LoginModule,HomeModule,ItemsModule,MoviesModule ],declarations: [ AppComponent ],providers: [ appRoutingProviders ],bootstrap: [ AppComponent ],})
    export class AppModule {}

app.routing.ts:

    import { ModuleWithProviders } from '@angular/core';
    import { Routes,RouterModule } from '@angular/router';
    const appRoutes: Routes = [];
    export const appRoutingProviders: any[] = [];
    export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

main.ts:

    import {platformbrowserDynamic} from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';
    const platform = platformbrowserDynamic();
    platform.bootstrapModule(AppModule);

system.config.js:

    /**
    * System configuration for Angular 2 samples
    * Adjust as necessary for your application needs.
    */
    (function (global) {
    System.config({
    paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
    },// map tells the System loader where to look for things
    map: {
    // our app is within the app folder
    app: 'app',// angular bundles
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js','@angular/common': 'npm:@angular/common/bundles/common.umd.js','@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js','@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js','@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js','@angular/http': 'npm:@angular/http/bundles/http.umd.js','@angular/router': 'npm:@angular/router/bundles/router.umd.js','@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js','@angular2-material': 'npm:@angular2-material',// other libraries
    'rxjs':                       'npm:rxjs','angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',},// packages tells the System loader how to load when no filename and/or no extension
    packages: {
    app: {
    main: './main.js',defaultExtension: 'js'
    },rxjs: {
    main: 'main.js','angular2-in-memory-web-api': {
    main: './index.js','@angular2-material/core': {
    main: 'core.js','@angular2-material/button': {
    main: 'button.js','@angular2-material/card': {
    main: 'card.js',defaultExtension: 'js'
    }
    }
    });
    })(this);

一旦我在“app.module.ts”的导入列表中添加MdButtonModule,我就开始收到错误.

更新2.0.0-alpha.9 cobalt-kraken(2016-09-26)

Angular Material has changed from @angular2-material/… packages to a
single package under @angular/material

所以您的配置可能如下所示:

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },// map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',// angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js','@angular/material': 'npm:@angular/material/bundles/material.umd.js',<== this line

       ...
    },...
  });
})(this);

并使用它

import { MaterialModule } from '@angular/material';
@NgModule({
  imports:      [ browserModule,MaterialModule ],bootstrap:    [ AppComponent ]
})
export class AppModule { }

旧版

从angular2-material alpha 8开始,您需要使用以下配置:

materialPackages.forEach(name => {
  packages[`@angular2-material/${name}`] = {
    format: 'cjs',main: `${name}.umd.js`
  };
});

另请参见更改日志

> https://github.com/angular/material2/blob/master/CHANGELOG.md

all: we’ve updated our packaging to match angular/angular’s packaging.
If you’re using SystemJS in your project,you will probably want to
switch to using our UMD bundles

所以你必须改变你的

system.config.js

packages: {
  ...
  '@angular2-material/core': {
    format: 'cjs',main: 'core.umd.js'
  },'@angular2-material/button': {
    format: 'cjs',main: 'button.umd.js'
  },'@angular2-material/card': {
    format: 'cjs',main: 'card.umd.js'
  },...

Angular2:应用程序启动时出错“http:// localhost:3000/traceur 404(找不到)”

Angular2:应用程序启动时出错“http:// localhost:3000/traceur 404(找不到)”

我有一个全新的安装Angular(rc1)。
我想我刚刚创建了通常的“Hello something”应用程序,但是,当我从浏览器启动应用程序,我得到以下错误在浏览器控制台

任何人可以解释我做错了什么?我必须有一些错误,因为其他更复杂的事情与rc1在我的机器上完美地工作。

提前致谢

app.component.ts

import { Component } from '@angular/core';

    @Component({
      selector: 'm2t-app',template: `
            Hello something
            `,directives: []
    })
    export class AppComponent { 
    }

主要

import { bootstrap }    from '@angular/platform-browser-dynamic';

import { AppComponent } from './app.component';

bootstrap(AppComponent);

index.html

<html>
  <head>
    <title>MEAN2 Training Class</title>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- 1. Load libraries -->
     <!-- polyfill(s) for older browsers -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-Metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err);  });
    </script>
  </head>

  <!-- 3. display the application -->
  <body>
    <m2t-app>Loading...</m2t-app>
  </body>
</html>

systemjs.confing.js

(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app',// 'dist','rxjs':                       'node_modules/rxjs','angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api','@angular':                   'node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',defaultExtension: 'js' },'rxjs':                       { defaultExtension: 'js' },'angular2-in-memory-web-api': { defaultExtension: 'js' },};

  var packageNames = [
    '@angular/common','@angular/compiler','@angular/core','@angular/http','@angular/platform-browser','@angular/platform-browser-dynamic','@angular/router','@angular/router-deprecated','@angular/testing','@angular/upgrade',];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js',defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js',defaultExtension: 'js' };
  });

  var config = {
    map: map,packages: packages
  }

  // filterSystemConfig - index.html's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);
我找到了原因。在app.component.ts开头,我已经评论了一个早期版本的愚蠢的AppComponent,类似
/*

import { AnotherComponent } from './anotherComponent.component'
// some other code

}*/
import { Component } from '@angular/core';

@Component({
  selector: 'm2t-app',template: `
        Hello something
        `,directives: []
})
export class AppComponent { 
}

删除文件开头的注释已解决了该问题。

API POST http://localhost:3000/[object%20Object]

API POST http://localhost:3000/[object%20Object]

如何解决API POST http://localhost:3000/[object%20Object]?

我正在制作带条纹的支付应用程序。 (基于条纹 repo)

我用 express 制作了 server.js。

当我点击支付按钮时,控制台显示xhr.js:177 POST http://localhost:3000/[object%20Object] 404 (Not Found) 这个错误。

enter image description here

server.js
const express = require(''express'');
const cors = require(''cors'');
const bodyParser = require(''body-parser'');
const path = require(''path'');
if (process.env.NODE_ENV !== ''production'') require(''dotenv'').config();
const stripe = require(''stripe'')(process.env.SECRET_KEY);

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

if (process.env.NODE_ENV === ''production'') {
  app.use(express.static(path.join(__dirname,''client/build'')));

  app.get(''*'',function (req,res) {
    res.sendFile(path.join(__dirname,''client/build'',''index.html''));
  });
}
app.listen(port,error => {
  if (error) throw error;
  console.log(''server running on port'' + port);
});

app.post(''/pay'',async (req,res) => {
  if (req.method === ''POST'') {
    try {
      const { amount } = req.body;
      const paymentIntent = await stripe.paymentIntents.create({
        amount,currency: ''usd'',});
      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500,message: err.message });
    }
  } else {
    res.setHeader(''Allow'',''POST'');
    res.status(405).end(''Method Not Allowed'');
  }
});

这是结账表格

Checkoutform.js
import React,{ useState } from ''react'';
import { CardElement,useStripe,useElements } from ''@stripe/react-stripe-js'';
import BillingDetailsFields from ''./BillingDetailForm'';
import axios from ''axios'';
import styled from ''styled-components'';
import payment_intents from ''./api/payment_intents'';

const CheckoutForm = ({ price,onSuccessfulCheckout }) => {
  const [isProcessing,setProcessingTo] = useState(false);
  const [checkoutError,setCheckoutError] = useState();

  const stripe = useStripe();
  const elements = useElements();

  const handleCardDetailsChange = ev => {
    ev.error ? setCheckoutError(ev.error.message) : setCheckoutError();
  };
  const handleFormSubmit = async e => {
    e.preventDefault();
    const billingDetails = {
      name: e.target.name.value,email: e.target.email.value,address: {
        city: e.target.city.value,line1: e.target.address.value,state: e.target.state.value,postal_code: e.target.zip.value,},};

    setProcessingTo(true);

    const cardElement = elements.getElement(''card'');

    try {
    const { data: clientSecret } = await axios.post(
      { payment_intents },{
        amount: price,}
    );
    console.log(clientSecret);

    const paymentMethodReq = await stripe.createPaymentMethod({
      type: ''card'',card: cardElement,billing_details: billingDetails,});

    if (paymentMethodReq.error) {
      setCheckoutError(paymentMethodReq.error.message);
      setProcessingTo(false);
      return;
    }

    const { error } = await stripe.confirmCardPayment(clientSecret,{
      payment_method: paymentMethodReq.paymentMethod.id,});

    if (error) {
      setCheckoutError(error.message);
      setProcessingTo(false);
      return;
    }

    onSuccessfulCheckout();
    } catch (err) {
      setCheckoutError(err.message);
    }
  };
  const cardElementOpts = {
    hidePostalCode: true,};
  return (
    <form onSubmit={handleFormSubmit}>
      <div>
        <CheckoutTitle>Pay with</CheckoutTitle>
        <BillingDetailsFields />
      </div>
      <div>
        <CardElementContainer>
          <CardElement
            option={cardElementOpts}
            onChange={handleCardDetailsChange}
          />
        </CardElementContainer>
      </div>
      <div>
        <PayBtn disabled={isProcessing || !stripe}>
          {isProcessing ? ''Processing...'' : `Confirm and Pay`}
        </PayBtn>
      </div>
    </form>
  );
};


我认为 app.post(''/pay'',res) => {} 有问题 但我真的不知道是什么问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

ASP.Net:尝试处理http:// localhost:5957 / http://yahoo.com时出现HTTP 400 Bad Request错误

ASP.Net:尝试处理http:// localhost:5957 / http://yahoo.com时出现HTTP 400 Bad Request错误

我正在尝试创建类似于diggbar的东西: http://digg.com/http://cnn.com

我正在使用Visual Studio 2010和Asp Development服务器.

但是,我无法让ASP dev服务器处理请求,因为它在路径中包含“http:”.我试图创建一个HTTPModule来重写BeginRequest中的URL,但是当url是http://localhost:5957/http://yahoo.com时,不会调用事件处理程序.如果url是http://localhost:5957/http/yahoo.com,则会调用事件处理程序

总结一下

> http://localhost:5957/http/yahoo.com有效
> http://localhost:5957/http//yahoo.com不起作用
> http://localhost:5957/http://yahoo.com不起作用
> http://localhost:5957/http:/yahoo.com不起作用

有任何想法吗?

解决方法@H_301_22@
我在Stefan的帮助下撰写了一篇文章,解释了如何做到这一点:

Experiments in Wackiness: Allowing percents,angle-brackets,and other naughty things in the ASP.NET/IIS Request URL

今天关于反应代理错误:无法将请求/ api /从localhost:3000代理到http:// localhost:8000ECONNREFUSED的介绍到此结束,谢谢您的阅读,有关angular – XHR错误(404 Not Found)加载http:// localhost:3000 / traceur、Angular2:应用程序启动时出错“http:// localhost:3000/traceur 404(找不到)”、API POST http://localhost:3000/[object%20Object]、ASP.Net:尝试处理http:// localhost:5957 / http://yahoo.com时出现HTTP 400 Bad Request错误等更多相关知识的信息可以在本站进行查询。

本文标签: