Search code examples
node.jsangularangular2-routing

How to serve a txt file in an Angular app


I have to follow these steps to verify my app, but I am having trouble making a route to link to my file.

https://i.sstatic.net/syNzC.jpg

The link above is the instructions I was given, I created the text file and I have it in my assets folder in my angular 2 app. However I have no idea how to create the route http://www.example.com/riot.txt so that it refers to my txt document file. Can anyone point me in the right direction? I'm using Angular 2.


Solution

  • You shouldn't need to create a route in Angular at all. If you're using the Angular CLI (or a similar setup) you can put the file in your src directory and add it to the assets property in the .angular-cli.json file.

    npm install -g @angular/cli
    ng new blog
    echo 'Hello, World' > src/greeting.txt
    

    Your .angular-cli.json would look like this.

    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": "blog"
      },
      "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets",
            "greeting.txt",
            "favicon.ico"
          ],
          "index": "index.html",
          "main": "main.ts",
          "polyfills": "polyfills.ts",
          "test": "test.ts",
          "tsconfig": "tsconfig.app.json",
          "testTsconfig": "tsconfig.spec.json",
          "prefix": "app",
          "styles": [
            "styles.css"
          ],
          "scripts": [],
          "environmentSource": "environments/environment.ts",
          "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts"
          }
        }
      ],
      "e2e": {
        "protractor": {
          "config": "./protractor.conf.js"
        }
      },
      "lint": [
        {
          "project": "src/tsconfig.app.json"
        },
        {
          "project": "src/tsconfig.spec.json"
        },
        {
          "project": "e2e/tsconfig.e2e.json"
        }
      ],
      "test": {
        "karma": {
          "config": "./karma.conf.js"
        }
      },
      "defaults": {
        "styleExt": "css",
        "component": {}
      }
    }
    

    Then you can run ng serve.

    ng serve
    

    As you can see, this is an issue in configuring your web server to serve static files - which most should by default.